logo Use CA10RAM to get 10%* Discount.
Order Nowlogo
(5/5)

Jupyter Notebook Best Practices

INSTRUCTIONS TO CANDIDATES
ANSWER ALL QUESTIONS

Python Assignment

#### <div class="alert alert-block alert-warning"> Read through this notebook and follow the instructions provided. In this assignment, you will complete the exercises that follow and submit your notebook (ipynb file) and html file to Canvas. Your files should include all output, i.e. run each cell and save before submitting for a grade.  In this course we will use only Python 3.x</div>

<div class="alert alert-block alert-info"><i>Each week we will be asking you to submit your completed notebook along with an html file. Some assignments will require additional types of files, so watch for that later on. Once you've run every cell in the notebook and you're satisfied with the results, submit the notebook and the html file to Canvas for grading. To download the html file to your computer, go to <u>File --> Download as --> HTML.</u></i></div>

![save-as-html-screenshot%20%28Custom%29.png](attachment:save-as-html-screenshot%20%28Custom%29.png)

<div class="alert alert-block alert-danger">

    

### Jupyter Notebook Best Practices

 

- Each time you come in to Jupyter Notebook (JN), start with a clean slate by clicking on `Kernel->Restart & Clear Output`.  This is done because of the following reasons:

  - Even if a cell is already showing output from a previous run, that does not mean the variables are active in the notebook.

  - If each necessary cell is not run beforehand, certain results may be incorrect or variables used later in the notebook will not be recognized and will generate an error . 

- In each week's assignment it's best if you run the code cells individually as you encounter them. Not running cells in sequence could cause incorrect answers to the assigned problems.

- Before you turn in your assignment, run your JN by clicking on `Kernel->Restart & Run All`.

  - This ensures that both the .ipynb and the HTML files turned in are complete for all assigned questions.

  - If your assignment has prompts (as the Module 1 assignment does), you will need to answer each prompt.

 

</div>

<div class="alert alert-block alert-danger"><b>Throughout all assignment notebooks you will see <font color=b>#TODO</font> instructions in most or all of the code cells provided for the assigned problems. <i><u>You are required to complete these as indicated to avoid any deductions.</u></i> Do not delete these or rearrange them. If you want to practice different approaches or techniques on your own that is certainly encouraged, but do so in your own separate personal notebook and not within this assignment notebook.</b></div>

### Exploring Jupyter Notebook `Help`

Take a moment to explore the resources provided above via `Help` in the menubar. Some are provided as a quick reference and are often sufficient to get basic guidance. For example, the `User Interface Tour` is a quick tour of the user interface in Jupyter notebook. There is also a link to documentation on some of the basics of Jupyter notebook in `Notebook Help`. Other resources in `Help` provide much lengthier guidance that you may want to reference later in the course.

### Keyboard Shortcuts

Jupyter notebook has many keyboard shortcuts that can be useful. A list of these shortcuts can be accessed from the toolbar above the `keyboard` icon or `Help --> Keyboard Shortcuts` from the menu bar. Another reference with keyboard shortcuts is provided in Canvas in the `Additional Resources` module. You can refer to either resource to answer the next question.

### Markdown Cells

When you insert a cell in your notebook it will be a code cell by default. To convert the cell to a Markdown cell, place your cursor in the cell then select `Markdown` from the drop-down menu in the toolbar. With a `Markdown` cell we can type as we normally would, then run the cell to display the formatted version. 

 

1. Single click on this cell to see that it is a markdown cell. This is indicated in the drop-down menu in the toolbar. 

 

2. Now double click on this cell and notice that you can see the behind the scenes HTML code.

 

You can create bullet points by using a dash (-).

- You can make words **bold**.

- You can make them <span style='color:red'>red</span>.

- You can <u>underline</u> them.

- You can <i>italicize</i> them.

 

3. Run the cell to return it to the formatted version.

### Code Cells

Another type of cell we will work with is a `code` cell, which is where we will do all of our programming. As mentioned above, when you insert a cell in a Jupyter notebook, the default is to create a code cell. Unlike a Markdown cell, to add comments to a code cell we need to use an alternative approach. A common method is to use the `hash` symbol, `#`:

#This is one way to add comments to your code.

#For each line of comments, a 'hash' symbol must be used while working in a code cell.

Another method of adding (**multiline**) comments within a `code` cell is to use triple quotations like the cell below:

'''When triple quotations are used, the comments will be enclosed by one set of quotations.

There is no need to start new quotations on each line. Just make sure all of your comments are wrapped

with quotations.'''

<div class="alert alert-block alert-success"><b>Problem 1 (2 pts.)</b>: Using either method shown above for commenting while working in a code cell, explain the advantages of including comments within a program in the code cell provided.</div>

 

<div class="alert alert-block alert-success"><b>Problem 2 (3 pts.)</b>: Convert the code cell provided to a markdown cell and name the three error types mentioned in Chapter 1 of this week's readings by creating bullet points.</div>

 

### Data Types

There are 3 data types that we will be exploring this week. They are `int`, `float`, and `str`. The `int` data type refers to any integer such as 1, -7, or 93. The `float` data type is short for floating decimal and refers to any real number (within a certain range of values) represented as a decimal.  For example, -2.0, 19.33, or 3.14159 have float type. The `str` data type refers to string of characters. Characters include letters, numerical digits, common punctuation marks (such as "." or "-"), and whitespace. Strings will be surrounded by `' '`, `" "`, `''' '''`, or `""" """`.

 

We can also use a type conversion function to convert from one type to another, for example, from an integer to a float or string or from a float to an integer or string. Only certain strings can be converted to an integer or float. If the string contains anything other than numbers, a `ValueError` will occur. This type of error occurs when you pass a parameter to a function that is a data type it is not expecting. For example, `float('3.882GPA')` will produce such an error since the letters GPA cannot be converted to a float. Later on in the course we will learn how to use `string methods` to manipulate strings to suit our purposes. For now, we will just explore a couple of the basics.

### Variables

To create and manipulate variables, we use **assignment statements**. These create new variables and give them values to refer to. The `=` in an assignment statement is an **assignment token** and does not represent equality like it does in mathematics. The assignment token assigns the value on the right to the name on the left.

The cell below has assigned values to different types of variables: `string`, `integer`, `float`, `Boolean`, and `null`. We will learn more about Boolean data types next week. No output will be generated when you run the next cell, but it is important that you run the cell because these variables will be loaded into memory and used later in this notebook.

# Python defined variables are global and hence can be recalled later on in any other cell

name = 'Albert' # this is a string, assigned to 'name'

height = 6      # this is an integer value, assigned to 'height'

weight = 181.389321    # this is a numeric (float) value, assigned to 'weight'

tValue = True   # this is a Boolean value, assigned to 'tValue'

flag = None     # this is a null variable in Python and has nothing defined for 'flag'

There are some rules to follow when naming variables. Variable names can contain letters (uppercase and lowercase), digits (0 - 9) and the underscore character `_`. They cannot contain spaces, cannot begin with a number, and cannot be a Python `keyword`. Be sure to reference the Python keywords in your readings for this week to avoid using them as a variable name. 

 

Lastly, a best practice when naming your variables is to create them in a way that describes their use in your program. For example, if you need a variable to define a type of car perhaps use `car` or `car_type` for the variable name instead of something generic like, `x` or `a`.

The data type of each variable created in the cell above is listed in the comments beside each one, but we can check each of them using the `type()` function. <i><u>Make sure you have run the cell above before running the following cells.</u></i>

type(weight)

Alternatively, we can determine the data type of several (or all) of the variables by separating each with a comma. When more than one is listed in this way, the result will display in the form of a `tuple`.

type(name), type(height), type(weight), type(tValue), type(flag)

Similarly, we can define variables using a comma separator and display them in the form of a tuple.

a, b = 3, 'strawberries'

a, b

### Basic `print()` Statements

The syntax to print a string is simply

```python

print('my string')

```

# Example of a basic print statement

print('Learning Python is fun!')

Keep in mind that we can wrap our string in single, double, or triple quotes. Single or double quotes are the most commonly used, but you can use whichever method you prefer. Feel free to try some different approaches and different strings in the cell below.

# Try printing your own string here

We could also print any of the variables we have predefined instead of a string.

print(name)

### Formatting Print Statements

Often times we want a statement to print instead of a simple string or the value of a variable. We can do this by formatting our print statements to be a combination of strings and values of variables. Print statements can be formatted nicely using various methods. One possibility is the `String` format method that works like this: 

print('My name is {} and I am {} feet tall.'.format(name, height))

As you may have guessed, the brackets `{}` represent format fields and are replaced with objects passed through them in the `str.format()` method. In this case we have already defined the variables `name` and `height` above, but we can still use this method without having predefined variables. </br>

 

The numbers in the brackets shown in this next cell refer to the position of each of an object from `format()`. We place these within our string(s) to indicate where they will each be passed. Remember the 1st position will be represented by `0`, the 2nd by `1`, etc. To see this, run the following cell:

print("{0} and {1} are my best friends.".format('Camille', 'Grace'))

However, if we switch the placement of the indices we get something different. Try running the cell below:

print("{2} and {0} have a dog named {1}.".format('Dominic','Bingo', 'Amber'))

We should point out that in each of these cases, the `print()` function is not needed. In other words, we can simply handle it this way:

"{2} and {1} have a dog named {0}.".format('Bingo','Dominic', 'Amber')

<i>However, you can see the difference in how the string is printed with this approach, so using **`print()` is the preferred method.**</i>

The `str.format()` method to create formatted print statements is nice, but it can be cumbersome if their are several parameters and lengthy strings. Another method of formatting print statements is to use `f-strings`. This is done by typing an `f` or `F` in front of the string and using `{}` to pass our variables through. One of the benefits of the f-string method is that it affords us more formatting options. The next cell demonstrates an example of this method:

print(f'{name} was {height} feet tall in high school and weighed about {weight:.2f} pounds.')

Notice this even rounded appropriately. In other words, it rounded to two decimals and rounded up with the last decimal because we used `.2f` to format the value of `weight` to two decimals. If we wanted zero decimals to appear for the weight, we could write it this way:

print(f'{name} was {height} feet tall in high school and weighed about {weight:.0f} pounds.')

Another option is to use the right side of the `:` to indicate the minimum number of characters to use. This can be useful to line up columns. Notice how the columns line up. Run the following cell and feel free to play around with the character lengths to see the effect.

print(f'{name:10} --> {height:5d} feet tall')

print(f'{name:10} --> {int(weight):5d} pounds')

We can also split our string over multiple lines. If we do this, each line in multiline string must begin with an `f`.

dog = 'Brutus'

dog_age = 4

cat = 'Ladybug'

cat_age = 11

my_name = 'Dave'

 

print(f'My name is {my_name}. '

     f'I have one dog and one cat. '

     f'My dog\'s name is {dog} and he is {dog_age} years old. '

     f'My cat\'s name is {cat} and she is {cat_age} years old. '

     )

Notice the use of `\` in front of the apostrophy inside of `dog's` and `cat's` in two of our sentences. This is needed because the print statement is surrounded by single quotes. The purpose of the backslash is so that the apostrophe is not interpretted as the end of the string. This is an instance when double quotes might be preferred so that the backslash is not needed.

We could also separate each sentence of our multiline string into one line for each. This is done using `\n` at the end of each line. This tells Python to start a new line at that point. Let's redo the previous example with double quotes and one line for each sentence.

dog = 'Brutus'

dog_age = 4

cat = 'Ladybug'

cat_age = 11

my_name = 'Dave'

 

print(f"My name is {my_name}.\n"

     f"I have one dog and one cat.\n"

     f"My dog's name is {dog} and he is {dog_age} years old.\n"

     f"My cat's name is {cat} and she is {cat_age} years old."

     )

These are just a few basic examples of how to format print statements nicely. For more details about powerful print options to play with, read through this article on __[f-strings](https://realpython.com/python-f-strings/)__. We will use formatted print statements throughout this course.

### Mathematical Operators

Python has several built-in operators, but the most basic operators are `mathematical` operators. There are several mathematical operators used in this week's readings - `+`, `-`, `*`, `/`, `**`, `%`, and `//`, which are used for various mathematical calculations.

To summarize these, the first four are addition, subtraction, multiplication, and division, respectively. These should each be self-explanatory. The double asterisk `**` represents exponentiation, i.e. `5**3` would result in `125`. The percent symbol, `%` is also called a `modulus operator`. It represents the remainder upon division. The double slash `//` will divide the first number by the second and truncate the result.

Here are some examples of `%` and `//` using Python as a calculator. In each case the result is an integer due to the nature of these operators.

# 27/4 has a remainder of 3

27 % 4

# 27/4 = 6.75 which truncates to 6

27 // 4

### Order of Operations

Just like all other calculators, Python will use the order of operations to calculate the numeric result. If parentheses are present, then the expression inside will be handled first. Then exponentiation followed by multiplication and division (working left to right), and finally addition and subtraction (working left to right). The next two examples demonstrate the difference in calculations with and without parentheses.

This first example is calculated as follows:

 

Exponentiation is first:

\begin{equation}

40^2 = 1600

\end{equation}

Then multiplication and division working left to right:

\begin{equation}

80/1600 = 0.05\\

0.05(4) = 0.2

\end{equation}

Last is subtraction:

\begin{equation}

7 - 0.2 = 6.8

\end{equation}

7 - 80 / 40**2 * 4

This next example is calculated as follows:

 

Parentheses are first:

\begin{equation}

7 - 80 = -73

\end{equation}

Next is exponentiation:

\begin{equation}

40^2 = 1600

\end{equation}

Last is multiplication and division working left to right:

\begin{equation}

-73/1600 = -0.045625\\

-0.045625(4) = -0.1825

\end{equation}

(7 - 80) / 40**2 * 4

### The `input()` function

In this week's readings you also learned about a built-in function in Python called `input`. When this is used in a program it will prompt the user to enter something such as a number or a string. It's helpful when creating a prompt to provide clear instructions for the user, such as `Enter your birthdate in the form MM/DD/YYYY` instead of `Enter your birthdate` or `Enter your monthly salary` instead of `Enter your salary`.

When we ask the user to input something, we need to assign that input to a variable. The general syntax of invoking the `input()` function is:

```python

variable = input('question')

```

A good habit to get into is to add an extra space at the end of your message for the prompt.

company = input('Where do you work? ') # Prompt the user to enter their company name

years = input('How many years have you worked there? ') # Prompt the user to enter their years of service

print(f'You have been working for {company} for {years} years.')

Keep in mind that the variable used with the input function will default to a string value unless told otherwise. In some cases this is fine, but if we try some type of mathematical calculation with `years`, Python will treat it like a string until we convert the variable:

type(years)

# Repeat the string 7 times

years*7

To convert the input from a `str` to an `int` (or `float`), we can do this with one of the type conversion functions. We can incorporate this into a single line of code by wrapping `input()` with `int()` or `float()` or add a separate line of code to convert the data type.

first_name = input('What is your first name? ')

last_name = input('What is your last name? ')

 

# Request year of birth and convert birth_year to an int type by wrapping input() with int()

birth_year = int(input('What year were you born? '))

 

# Calculate the user's age in 2035 and assign this to the variable 'age_2035'

age_2035 = 2035 - birth_year

 

# Create a formatted print statement to display the user's age in 2035

print(f'{first_name} {last_name} will turn {age_2035} years old in 2035.')

We might also want to modify the string input entered by the user using string methods. For example, we might want to change the case of the name entered by the user above. We will do more with string methods later on in the course, but there are a few basic string methods we want to introduce now. The first we want to introduce is `capitalize`. This method converts the first letter of a string to uppercase:

fruit = 'apple'

print(fruit)

new_fruit = fruit.capitalize() #string method

print(new_fruit)

We could also convert every letter in a string to uppercase using the `upper()` method or to lowercase using the `lower()` method.

street = 'Elm'

my_street = street.upper() # Call the upper() method on the object 'street'

print(my_street)

 

password = 'GQskUXr'

new_password = password.lower() # Call the lower() method on the object 'password'

print(new_password)

<div class="alert alert-block alert-success"><b>Problem 3 (5 pts.)</b>: Create a simple code snippet that causes one of the three types of errors listed in Problem 2 then fix the error. <br><br>

1. Create your code snippet in the code cell provided and include comments to explain each line of your code.<br>

2. Add a markdown cell below the code cell provided and explain the error and what is causing the error.<br>

3. Add another new cell below your markdown cell that fixes the error.</div>

#TODO: Create a code snippet that generates one of the errors listed in Problem 2.

 

<div class="alert alert-block alert-success"><b>Problem 4 (6 pts.)</b>: Write a program to calculate gas mileage.<br><br>

1. Prompt the use to enter the type of car they drive.<br>

2. Prompt the user to enter the number of miles they've traveled since their last fill up.<br>

3. Prompt the user to enter the number of gallons it took to fill up since their last tank of gas.<br>

4. Calculate the gas mileage.<br>

5. Create a formatted print statement to let the user know their gas mileage for their car.<br> 

 

<i><u>Be sure to follow along with the instructions provided in the <font color=b><b>#TODO</b></font> instructions as written.</u></i><br><br>

**Word your prompts and output message the same as the following:**

</div>

 

`Enter the make and model of your car: Lexus RX350

Enter the number of miles you traveled since your last fill up: 289.5

Enter the number of gallons of gas it took to fill up this time: 16.333

You traveled 290 miles on 16.33 gallons of gas.

Your Lexus RX350 averaged 17.7 miles per gallon.`

#TODO: Prompt the use to enter make and model of their car:

 

 

#TODO: Prompt the user to enter the number of miles they've traveled since their last fill up

 

 

#TODO: Prompt the user to enter the number of gallons it took to fill up

 

 

#TODO: Create a variable called 'mpg' that calculates the miles per gallon

 

 

#TODO: Create a formatted print statement that rounds appropriately and generates the same output shown above

 

You will need the following formula to complete the next problem. For simplicity, we will assume payments would be made monthly and the interest would be compounded monthly.

 

Use the following formula to calculate a monthly payment:

\begin{equation}

M = P\left[ \frac{r\left( 1+r\right)^n}{\left( 1+r\right)^n-1} \right]

\end{equation}

 

The variables are defined as follows:<br><br>

\$ r\$ = The annual interest rate converted to a decimal then divided by \$ 12\$<br>

\$ n\$ = The total number of monthly payments for the duration of the loan<br>

\$P \$ = The principal (or loan) amount<br>

\$M \$ = The monthly payment

<div class="alert alert-block alert-success"><b>Problem 5 (6 pts.)</b>: Calculate a loan payment.<br><br>

1. Prompt the user to enter the amount they are borrowing.<br>

2. Prompt the user to enter the duration of the loan in months.<br>

3. Prompt the user to enter the annual interest rate.<br>

4. Calculate the monthly payment.<br>

5. Create a formatted print statement to display the montly payment.<br>

 

**Word your prompts and your output message the same as the following:**</div>

`Enter the amount you are borrowing: 50000

Enter the duration of the loan in months: 60

Enter the annual interest rate: 2.5

Your monthly payment will be $887.37`

#TODO: Prompt the user to enter the amount the user is borrowing.

 

 

#TODO: Prompt the user to enter the duration of the loan in months.

 

 

#TODO: Prompt the user to enter the annual interest rate.

 

 

#TODO: Calculate the monthly payment.

 

 

#TODO: Create a formatted print statement to display the monthly payment.

 

<div class="alert alert-block alert-danger">Be sure to <i><u>run all cells in your notebook</u></i> then submit the following two files for a grade:

    

 

1. Your completed <b>notebook</b>

2. Your <b>html file</b>

 

</div>

 

(5/5)
Attachments:

Expert's Answer

352 Times Downloaded

Related Questions

. Introgramming & Unix Fall 2018, CRN 44882, Oakland University Homework Assignment 6 - Using Arrays and Functions in C

DescriptionIn this final assignment, the students will demonstrate their ability to apply two ma

. The standard path finding involves finding the (shortest) path from an origin to a destination, typically on a map. This is an

Path finding involves finding a path from A to B. Typically we want the path to have certain properties,such as being the shortest or to avoid going t

. Develop a program to emulate a purchase transaction at a retail store. This program will have two classes, a LineItem class and a Transaction class. The LineItem class will represent an individual

Develop a program to emulate a purchase transaction at a retail store. Thisprogram will have two classes, a LineItem class and a Transaction class. Th

. SeaPort Project series For this set of projects for the course, we wish to simulate some of the aspects of a number of Sea Ports. Here are the classes and their instance variables we wish to define:

1 Project 1 Introduction - the SeaPort Project series For this set of projects for the course, we wish to simulate some of the aspects of a number of

. Project 2 Introduction - the SeaPort Project series For this set of projects for the course, we wish to simulate some of the aspects of a number of Sea Ports. Here are the classes and their instance variables we wish to define:

1 Project 2 Introduction - the SeaPort Project series For this set of projects for the course, we wish to simulate some of the aspects of a number of

352 Times Downloaded

Ask This Question To Be Solved By Our ExpertsGet A+ Grade Solution Guaranteed

expert
Um e HaniScience

549 Answers

Hire Me
expert
Muhammad Ali HaiderFinance

635 Answers

Hire Me
expert
Husnain SaeedComputer science

668 Answers

Hire Me
expert
Atharva PatilComputer science

572 Answers

Hire Me

Get Free Quote!

448 Experts Online