Make me look good. Click on the cell below and press Ctrl+Enter.
from IPython.core.display import HTML
HTML(open('css/custom.css', 'r').read())
Jupyter is an interactive computational environment where you can combine code, text and graphs in notebooks.
You're looking at a Jupyter notebook right now!
Until recently, Jupyter was called IPython Notebook. This historical tidbit might help if you're looking for other references.
We'll be using Jupyter with the Python programming langugage in this course.
A notebook consists of a sequence of cells of different types.
We'll use these types of cells frequently:
You can determine the type of a cell in the toolbar.
You can run a cell by:
In a code cell, you can edit and write Python code.
Let's write some Python code that prints a friendly message:
print('Hello world!')
Hello world!
The print()
function prints to the screen whatever is inside the parentheses.
Note that a code cell has
In a Markdown cell, you can enter text to write notes about your code and document your workflow.
For example, this cell is a Markdown cell.
The Markdown language is a popular way to provide formatting (e.g. bold, italics, lists) to plain text. Use Google to find documentation and tutorials. Here's a pretty good cheat sheet.
For now, here are a few basic, useful Markdown constructs:
You can format text as italic with *asterisks* or _underscores_.
You can format text as bold with **double asterisks** or __double underscores__.
To write an bulleted list, use *, -, or + as bullets, like this:
* One
* Two
* Three
To edit a Markdown cell, double-click it. When you're done editing it, run the cell.
Try it in the cell below:
Double-click to edit this cell. Try out Markdown here.
You can insert a new cell by selecting Insert → Insert Cell Above/Below in the menu bar.
You can copy and paste cells using the Edit menu.
You can also split, merge, move, and delete cells using the Edit menu.
Jupyter autosaves your notebook every few minutes.
To manually save, click the icon in the toolbar, or select File → Save and Checkpoint.
To close the notebook, select File → Close and Halt.
We'll go over some other features of Jupyter later.
There are many resources out there on using Jupyter — Google is your friend!
print('Hello world!')
Hello world!
A variable is a label that is assigned to a value, or some piece of information.
We can define a variable using the =
sign.
Using variables, we can accomplish the same thing as the code above:
message = 'Hello world!'
print(message)
Hello world!
Note that print()
prints the value of a variable.
We can change the value of a variable at any time.
Variables are important because they allow us to represent information in a flexible way.
A comment allows us to write notes to ourselves or others in our code.
As our code becomes more complicated, it'll be very useful to add comments that describe what our code is doing.
In Python, the hash mark (#
) indicates a comment.
Anything following a hash mark in your code is ignored by Python.
# This is a comment. Python will not try to run this line of code.
print("This is not a comment. Python will run this line of code.")
This is not a comment. Python will run this line of code.
An integer is a whole number.
A float is any number with a decimal point.
Python differentiates between integers and floats.
We can use the type()
function to check the type of a number.
# What is the type of 7?
print(type(7))
<class 'int'>
# What is the type of 2.3?
print(type(2.3))
<class 'float'>
Symbol | Operation | Example |
---|---|---|
* | Multiplication | 15 * 7 |
/ | Division | 33 / 15 |
+ | Addition | 3.7 + 4.4 |
- | Subtraction | 10 - 5 |
** | Exponentiation | 2**4 |
% | Mod | 20 % 8 |
# What is 15 times 7?
print(15 * 7)
105
# What is 3.7 plus 4.4?
print(3.7 + 4.4)
8.100000000000001
Sometimes you get an arbitrary number of decimal places when doing math with floats.
Python defaults to a float in any operation that uses a float, even if the output is a whole number.
You can use variables to represent numbers, and then perform arithmetic operations on variables.
Let's find the area of a rectangle:
# Define dimensions of a rectangle
length = 30
width = 40
# Compute area
area = length * width
# Print area
print(area)
1200
print(volume)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-11-14ae0d839e78> in <module> ----> 1 print(volume) NameError: name 'volume' is not defined
# Define height of box
height = 10
# Compute volume
volume = length * width * height
# Print volume
print(volume)
12000
Note that the prompt numbers next to the code cells (e.g. In [3]
and Out [3]
) indicate which cells have been run and in which order.
This is very useful, especially if you are running cells out-of-sequence.
Quick check. What does the following code output?
print(type(volume))
Write your notes here. Double-click to edit.
Strings are lists of printable characters defined using either double quotes or single quotes.
For example:
"This is a string."
'This is also a string.'
# Define two variables assigned to strings
test_string_1 = "This is a string."
test_string_2 = 'This is also a string.'
# Print the type of these two variables
print(test_string_1)
print(test_string_2)
This is a string. This is also a string.
'Scooby Doo! ' + 'Where are you??'
Write your notes here. Double-click to edit.
# Try it out!
print('Scooby Doo! ' + 'Where are you??')
Scooby Doo! Where are you??
A method is an action that Python can perform on a piece of data.
Strings have many methods. For example, we can change the case of the words in a string:
# Define a variable assigned to my name
my_name = 'nelson uhan'
# Make this string all uppercase
print(my_name.upper())
# Make this string all lowercase
print(my_name.lower())
NELSON UHAN nelson uhan
The official Python documentation is here.
The official documentation can be intimidating to read and navigate at first.
You may find your textbook easier to use, especially in the beginning.
Google can also be quite helpful 🙂
You can find the official Python documentation on string methods here.
Click on the link. What does the .title()
method do to a string?
Write your notes here. Double-click to edit.
# Define a variable for your neighbor's name
neighbor = 'Nelson'
# Print the value of the 'neighbor' variable
print(f'My neighbor is {neighbor}.')
My neighbor is Nelson.
To insert a variable's value into a string:
f
immediatley before the opening quotation markThese strings are called f-strings
Example. Define three variables, left
, right
, me
, containing the names of your neighbors and yourself. Use the print()
function to print the values of these variables in one line.
# Define variables
left = 'Alice'
right = 'Carol'
me = 'Nelson'
# Print values of variables
print(f"I'm {me}, my neighbor to the left is {left}, and my neighbor to the right is {right}.")
I'm Nelson, my neighbor to the left is Alice, and my neighbor to the right is Carol.
A list is a collection of items that are organized in a particular order.
You can think of a list as an array or a vector.
A list is written as a sequence of comma-separated items between square brackets.
# Define a list containing the first 5 square numbers
squares = [0, 1, 4, 9, 16]
# Define a list containing the days of the week
days_of_the_week = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
Lists have methods too.
What do you think the following code does?
squares.reverse()
print(squares)
Write your notes here. Double-click to edit.
# Try it out!
squares.reverse()
print(squares)
[16, 9, 4, 1, 0]
days_of_the_week.sort()
print(days_of_the_week)
Write your notes here. Double-click to edit.
# Try it out!
days_of_the_week.sort()
print(days_of_the_week)
['Fri', 'Mon', 'Sat', 'Sun', 'Thu', 'Tue', 'Wed']
len()
function:# How many days of the week are there?
print(len(days_of_the_week))
7
sum()
function:# What is the sum of the first 5 square numbers?
print(sum(squares))
30
In Python, indexing (that is, counting) starts at 0!
Suppose we defined a variable assigned to a string like this:
x = 'Python'
Index | 0 | 1 | 2 | 3 | 4 | 5 |
---|---|---|---|---|---|---|
Value | 'P' |
'y' |
't' |
'h' |
'o' |
'n' |
How to access | x[0] |
x[1] |
x[2] |
x[3] |
x[4] |
x[5] |
# Define a variable assigned to a string
x = 'Python'
# Print the 1st character of the string
print(x[0])
# Print the 4th character of the string
print(x[3])
P h
# Define (again) a list containing the days of the week
days_of_the_week = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
# Print the 5th day of the week
print(days_of_the_week[4])
Thu
Variable names can only contain letters, numbers, and underscores.
Variable names cannot start with a number.
Spaces are not allowed! Use underscores instead.
Avoid using Python keywords and function names — these are words that Python has reserved for a particular programmatic purpose.
print
— how will Python know if you want to use the print()
function or your variable called print
?Variable names should be short but descriptive.
name
is better than n
student_name
is better than s_n
name_length
is better than length_of_persons_name
Problem 1. (PCC 2-4: Name Cases) Store a person’s name in a variable, and then print that person’s name in lowercase, uppercase, and titlecase.
# Write your code here
my_name = 'nelson uhan'
# Lowercase
print(my_name.lower())
# Uppercase
print(my_name.upper())
# Titlecase
print(my_name.title())
nelson uhan NELSON UHAN Nelson Uhan
Problem 2. (PCC 2-7: Stripping Names) First, read about whitespace on page 22 of PCC.
Store a person’s name, and include some whitespace characters at the beginning and end of the name. Make sure you use each character combination, \t
and \n
, at least once. Print the name once, so the whitespace around the name is displayed. Then print the name using each of the three stripping functions, lstrip()
,
rstrip()
, and strip()
.
# Write your code here
my_name = ' Nelson\tUhan \n'
# Print with whitespace
print("With all whitespace:")
print(my_name)
# Print with stripping functions
print("With lstrip():")
print(my_name.lstrip())
print("With rstrip():")
print(my_name.rstrip())
print("With strip():")
print(my_name.strip())
With all whitespace: Nelson Uhan With lstrip(): Nelson Uhan With rstrip(): Nelson Uhan With strip(): Nelson Uhan
Problem 3. The drug company Mylan manufactures, markets, and sells EpiPens in the U.S. market. EpiPens, as displayed below, provide an easy-to-use auto-injector, which enables untrained staff or even children to deliver life-saving medicine in the event of a severe allergic reaction.
In 2004, a pack of 2 EpiPens sold for \$57. Mylan has been raising the price of EpiPens each year and in 2016, one purchaser paid \$600 per pack. Congress is getting involved and public anger is being trained on Mylan, which seems to be profiteering from its position as the only U.S. provider of this kind of device.
Find the change in price, the percentage increase in price, and compute the yearly rate of inflation (as percentage increase). What assumptions are you making in your calculation?
# Write your code here
# Define variables for prices in 2004 and 2016
price_2004 = 57
price_2016 = 600
# Change in price
price_change = price_2016 - price_2004
print(f'Change in price = {price_change}')
# Percentage increase in price
pct_price_change = ((price_2016 - price_2004) / price_2004 - 1) * 100
print(f'Percentage change in price = {pct_price_change} %')
# Yearly rate of inflation
yearly_inflation_rate = pct_price_change / (2016 - 2004 + 1)
print(f'Yearly inflation rate = {yearly_inflation_rate} %')
Change in price = 543 Percentage change in price = 852.6315789473686 % Yearly inflation rate = 65.58704453441297 %
Write your assumptions here. Double-click to edit.
In the above calculations, we are assuming that the price changes linearly from year-to-year.
Problem 4. (Adapted from a problem due to John Dalbey at CalPoly) A cyclist is coasting on a level road. The cyclist's initial speed is 10 miles/hour. After coasting for 1 minute, the cyclist's final speed is 2.5 miles/hour. The rate of acceleration $a$ can be computed using the formula:
\begin{equation*} a = \frac{V_\text{final} -V_\text{initial}}{\text{duration}}. \end{equation*}Compute the acceleration of the cyclist.
# Write your code here
# Define problem data
v_initial = 10
v_final = 2.5
duration = 1 / 60 # in hours
# Compute acceleration
acceleration = (v_final - v_initial) / duration
print(f'Acceleration = {acceleration} miles / hour squared')
Acceleration = -450.0 miles / hour squared
Problem 5. (PCC 3-8: Seeing the World)
First, read pages 43-45 in PCC to learn about sorting lists temporarily vs. permanently.
Think of at least five places in the world you’d like to visit.
sorted()
to print your list in alphabetical order without modifying the actual list.sorted()
to print your list in reverse alphabetical order without changing the order of the original list.reverse()
to change the order of your list. Print the list to show that its order has changed.reverse()
to change the order of your list again. Print the list to show it’s back to its original order.sort()
to change your list so it’s stored in alphabetical order. Print the list to show that its order has been changed.sort()
to change your list so it’s stored in reverse alphabetical order. Print the list to show that its order has changed.# Write your code here
# List of places to visit
places_to_visit = ['Vietnam', 'New Zealand', 'Australia', 'India', 'Israel']
# Print original list
print('Original list:')
print(places_to_visit)
# Temporarily alphabetically sorted list
print('Temporarily alphabetically sorted list:')
print(sorted(places_to_visit))
print('Original list:')
print(places_to_visit)
# Temporarily reverse alphabetically ordered list
print('Temporarily reverse alphabetically ordered list:')
print(sorted(places_to_visit, reverse=True))
print('Original list:')
print(places_to_visit)
# Permanently reverse list (not reverse alphabetically sorted)
places_to_visit.reverse()
print('Permanently reverse list:')
print(places_to_visit)
# Permanently alphabetically sorted list
places_to_visit.sort()
print('Permanently alphabetically sorted original list:')
print(places_to_visit)
Original list: ['Vietnam', 'New Zealand', 'Australia', 'India', 'Israel'] Temporarily alphabetically sorted list: ['Australia', 'India', 'Israel', 'New Zealand', 'Vietnam'] Original list: ['Vietnam', 'New Zealand', 'Australia', 'India', 'Israel'] Temporarily reverse alphabetically ordered list: ['Vietnam', 'New Zealand', 'Israel', 'India', 'Australia'] Original list: ['Vietnam', 'New Zealand', 'Australia', 'India', 'Israel'] Permanently reverse list: ['Israel', 'India', 'Australia', 'New Zealand', 'Vietnam'] Permanently alphabetically sorted original list: ['Australia', 'India', 'Israel', 'New Zealand', 'Vietnam']
Problem 6. Define a list L = [1,4,7,10]
. Find the sum of the 2nd and 4th elements of L
. Find the sum of all the elements of L
.
# Write your code here
# Define given list
L = [1, 4, 7, 10]
# Sum of 2nd and 4th elements of L
sum_2_4 = L[1] + L[3]
print(f'Sum of 2nd and 4th elements of L = {sum_2_4}')
# Sum of all elements of L
sum_all = sum(L)
print(f'Sum of all elements of L = {sum_all}')
Sum of 2nd and 4th elements of L = 14 Sum of all elements of L = 22