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())
matplotlib
A for loop allows you to perform the same task or set of tasks on every item in a list.
For example, suppose we have a list of band member names. We can use a for
loop to print each name in the list:
# A list containing the names of the members of The Band
the_band = ['Robbie Robertson', 'Levon Helm', 'Richard Manuel', 'Rick Danko', 'Garth Hudson']
# Print each member's name
for name in the_band:
print(name)
# How do we write code outside the for loop?
print('And those are the members of The Band!')
Robbie Robertson Levon Helm Richard Manuel Rick Danko Garth Hudson And those are the members of The Band!
for name in the_band:
print(name)
Often we will want to write a for
loop over consecutive integers.
We can do this using the range()
function, like this:
# Print the first five integers, starting at 0
for i in range(5):
print(i)
0 1 2 3 4
range(n)
starts at 0
, increases by 1
until n - 1
.range(start, stop)
starts at start
, increases by 1
until stop - 1
.range(start, stop, step)
starts at start
, increases by step
until stop - 1
is reached or passed.Example. Use a for
loop to print the even numbers starting at 10 and ending at 20.
# Write your code here
for i in range(10, 21, 2):
print(i)
10 12 14 16 18 20
We can use for
loops to repeatedly do something to a variable.
For example, we can add the integers from 1 to 10:
# Create a variable to stored the total value
total = 0
# Add 1 to 10 to the total value, one at a time
for i in range(1, 11):
# total += i is the same as total = total + i
total += i
# Print the total
print(total)
55
from IPython.display import IFrame
IFrame('http://pythontutor.com/iframe-embed.html#code=%23%20Create%20a%20variable%20to%20stored%20the%20total%20value%0Atotal%20%3D%200%0A%0A%23%20Add%201%20to%2010%20to%20the%20total%20value,%20one%20at%20a%20time%0Afor%20i%20in%20range%281,%2011%29%3A%0A%20%20%20%20%23%20total%20%2B%3D%20i%20is%20the%20same%20as%20total%20%3D%20total%20%2B%20i%0A%20%20%20%20total%20%2B%3D%20i%0A%0A%23%20Print%20the%20total%0Aprint%28total%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false', width=800, height=450)
Note that total += i
is indented, while print(total)
is not indented.
These indentation levels are very important in Python code!
See what happens if you move the print()
statement inside the for
loop by changing its indentation level to match that of total += i
.
Recall list indexing from the previous lesson.
Quick review. How do we get the 3rd element of the list defined below?
# Define a list of fruits
fruits = ['banana', 'apple', 'pear', 'orange', 'grapes', 'watermelon', 'kiwi']
# Print the 3rd element of the list of fruits
print(fruits[2])
pear
Slicing is like indexing on steroids. 🤪
A slice is a specific group of items in a list.
my_list[start:stop]
gives you a new list containing the elements of my_list
whose indices start at start
and end at stop - 1
.
my_list[start:stop:step]
gives you a new list containing the elements of my_list
whose indices start at start
, and increase by step
until stop - 1
is reached or passed.
# Print the 3rd, 4th, and 5th fruits
print(fruits[2:5])
['pear', 'orange', 'grapes']
# Print the 1st, 3rd, and 5th fruits
print(fruits[0:5:2])
['banana', 'pear', 'grapes']
If you omit start
, Python automatically starts your slice at the beginning of my_list
.
If you omit stop
, Python automatically ends your slice at the end of my_list
.
If you omit step
, Python automatically assumes a step value of 1.
# Print the 4th fruit onwards
print(fruits[3:])
['orange', 'grapes', 'watermelon', 'kiwi']
list()
and range()
¶One task we'll need to do often is to build lists of numbers with a particular pattern.
One way to do this is to use list()
with range()
.
If we want a list of the integers between 1 and 5 (inclusive), we can write:
# Create list of numbers between 1 and 5 inclusive
integers = list(range(1, 6))
# Print the list
print(integers)
[1, 2, 3, 4, 5]
.append()
¶.append()
:# Add guava to the list of fruits defined above
fruits.append('guava')
# Print the list of fruits
print(fruits)
['banana', 'apple', 'pear', 'orange', 'grapes', 'watermelon', 'kiwi', 'guava']
# Start with empty list
another_integers = []
# Iterate over the numbers between 1 and 5
# Add each of these numbers to the list
for i in range(1, 6):
another_integers.append(i)
# Print the list
print(another_integers)
[1, 2, 3, 4, 5]
from IPython.display import IFrame
IFrame('http://pythontutor.com/iframe-embed.html#code=%23%20Start%20with%20empty%20list%0Aanother_integers%20%3D%20%5B%5D%0A%0A%23%20Iterate%20over%20the%20numbers%20between%201%20and%205%0A%23%20Add%20each%20of%20these%20numbers%20to%20the%20list%0Afor%20i%20in%20range%281,%206%29%3A%0A%20%20%20%20another_integers.append%28i%29%0A%20%20%20%0A%23%20Print%20the%20list%0Aprint%28another_integers%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=false&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false', width=800, height=450)
Example. Build a list of the decimal numbers $1.0, 1.1, 1.2, \dots, 4.9, 5.0$. Print the list.
# Write your code here
decimals = []
for i in range(41):
decimals.append(1.0 + 0.1 * i)
print(decimals)
[1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7000000000000002, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4000000000000004, 2.5, 2.6, 2.7, 2.8, 2.9000000000000004, 3.0, 3.1, 3.2, 3.3000000000000003, 3.4000000000000004, 3.5, 3.6, 3.7, 3.8000000000000003, 3.9000000000000004, 4.0, 4.1, 4.2, 4.300000000000001, 4.4, 4.5, 4.6, 4.7, 4.800000000000001, 4.9, 5.0]
If you want to do something in Python, there's a very good chance that there's a package that will help you out.
Anaconda, the Python distribution we're using in this class, comes with many useful libraries.
You can also install libraries pretty easily — we'll do this later in the course. (Actually, we already did it with Pyomo.)
import
it so that we can access its functions, like this:import matplotlib.pyplot as plt
as plt
in the cell above lets us refer to matplotlib.pyplot
as plt
.# Create a figure
fig = plt.figure()
# Draw axes on the figure
ax = fig.add_subplot(1, 1, 1)
# Create list of values on the x-axis between 0 and 5, with an increment of 0.1
x_values = []
for i in range(51):
x_values.append(0.1 * i)
# Create list of corresponding y values
y_values = []
for x in x_values:
y_values.append(x**2)
# Plot the data on the axes
ax.plot(x_values, y_values)
# Label the axes
ax.set_xlabel('x')
ax.set_ylabel('y')
# Give the plot a title
ax.set_title('A Parabola Using Matplotlib')
# Show the figure
plt.show()
Some notes about the above code:
x_values
and y_values
are lists of the same size.
plt.plot(x_values, y_values)
plots the points
(x_values[0]
, y_values[0]
), (x_values[1]
, y_values[1]
), (x_values[2]
, y_values[2]
), ...
and connects all these points (by default). You can change this behavior (connected or not connected, colors, shapes, etc.): see the documentation.
ax.set_xlabel()
and ax.set_ylabel()
label the horizontal and vertical axes, respectively.
ax.set_title()
sets the title for the axes.
Problem 1. (PCC 4-1: Pizzas) Think of at least three kinds of your favorite pizza. Store these pizza names in a list, and then use a for
loop to print the name of each pizza.
for
loop to print a sentence using the name of the pizza instead of printing just the name of the pizza. For each pizza you should have one line of output containing a simple statement like:I like pepperoni pizza.
I really love pizza!
# Write your code here
# Build list of pizzas
pizzas = ['Mushroom', 'Pepperoni', 'Sausage and Pineapple']
# Print pizza names
for p in pizzas:
print(p)
# Print sentences about pizzas
for p in pizzas:
print(f'I like {p} pizza.')
# Print a final sentence about pizza
print('I really love pizza!')
Mushroom Pepperoni Sausage and Pineapple I like Mushroom pizza. I like Pepperoni pizza. I like Sausage and Pineapple pizza. I really love pizza!
Problem 2. (PCC 4-11: My Pizzas, Your Pizzas)
Read about copying lists on page 63 of PCC.
Start with your code from Problem 1. Make a copy of the list of pizzas, and call it friend_pizzas
. Then, do the following:
friend_pizzas
.My favorite pizzas are:
, and then use a for
loop to print the first list.My friend’s favorite pizzas are:
, and then use a for
loop to print the second list.# Write your code here
# Create copy of list of pizza names called friend_pizzas
friend_pizzas = pizzas[:]
# Add a new pizza to the original list
pizzas.append('Black Olives')
# Add a different pizza to the new list
friend_pizzas.append('Kale and Broccoli')
# Print my favorite pizzas
print('My favorite pizzas are:')
for p in pizzas:
print(p)
# Print my friend's favorite pizzas
print("My friend's favorite pizzas are:")
for p in friend_pizzas:
print(p)
My favorite pizzas are: Mushroom Pepperoni Sausage and Pineapple Black Olives My friend's favorite pizzas are: Mushroom Pepperoni Sausage and Pineapple Kale and Broccoli
Problem 3. (PCC 4-15: Code Review)
Read about styling your code on pages 68-70 of PCC.
Modify the code that you've written for Problems 1 and 2 to comply with PEP 8:
Problem 4. Construct a list consisting of all the odd numbers from 1 to 55. Print the list.
# Write your code here
# Using list() and range()
odd_numbers = list(range(1, 56, 2))
print(odd_numbers)
# Alternative solution: using .append()
odd_numbers2 = []
for i in range(28):
odd_numbers2.append(1 + 2 * i)
print(odd_numbers2)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55] [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55]
Problem 5. Use a for
loop to find $\sum_{k=1}^{1000} \frac{1}{k^3}$.
# Write your code here
# Initialize the total value of the sum to zero
total = 0
# Iterate k from 1 to 1000, adding 1/k^3 at each step
for k in range(1, 1001):
total += (1 / k**3)
print(f'The sum evaluates to {total}.')
# Alternative solution: build a list of the values of 1/k^3 first, then use sum()
values = []
for k in range(1, 1001):
values.append(1 / k**3)
total2 = sum(values)
print(f'The sum evaluates to {total2}.')
The sum evaluates to 1.2020564036593433. The sum evaluates to 1.2020564036593433.
Problem 6. Using Matplotlib, plot a graph of $y = \sin(x)$ for values of $x$ between 0 and 5. Use points on the $x$-axis that are 0.1 apart. Label your axes and title your plot.
You can use the sin()
function from the math
library. Make sure to import the math
library first:
import math
Then to compute $\sin(x)$, you can write math.sin(x)
.
# Write your code here
import matplotlib.pyplot as plt
import math
# Create a figure object
fig = plt.figure()
# Draw an axis object on the figure
ax = fig.add_subplot(1, 1, 1)
# Create list of sample points on the x-axis
# between 0 and 5, with an increment of 0.1.
x_values = []
for i in range(51):
x_values.append(0.1 * i)
# Create list of corresponding points in the y-direction
y_values = []
for x in x_values:
y_values.append(math.sin(x))
# Plot the data
plt.plot(x_values, y_values)
# Label the axes
ax.set_xlabel('x')
ax.set_ylabel('y')
# Give the plot a title
ax.set_title('sin(x)')
# Show the figure
plt.show()
Problem 7. Compute the sum of the numbers 1, 2, ..., 1000. You can use a for
loop, or you can use the sum()
function applied to a list.
Let L
be the list of numbers 1, 2, ..., 1000. Let M = sorted(L, reverse=True)
. Add L
and M
. What do you notice? Is it easy to add the numbers in L + M
? Can you do it in your head? How are the sums of L
, M
and L + M
related? Can you see what Gauss did? If so, you should be able to give an algebraic expression for the sum of the numbers from 1 to 1000, without using Python.
C. F. Gauss is featued on the German 10DM bill, alongside the graph of the Gaussian distribution from Statistics, buildings at the University of Göttingen, and (on the reverse side), an outline of the German state of Hannover, which Gauss surveyed. Some of the greatest mathematicians were professors at Göttingen, including Gauss, Riemann and Hilbert.
# Write your code here
# Using a for loop
sum_of_numbers = 0
for i in range(0, 1001):
sum_of_numbers += i
print(f'The sum of the numbers 1, 2, ..., 1000 is {sum_of_numbers}')
# Using sum()
list_of_numbers = list(range(0, 1001))
sum_of_numbers2 = sum(list_of_numbers)
print(f'The sum of the numbers 1, 2, ..., 1000 is {sum_of_numbers2}')
The sum of the numbers 1, 2, ..., 1000 is 500500 The sum of the numbers 1, 2, ..., 1000 is 500500
Problem 8. The Fibonacci numbers are defined in the following way. The first and second Fibonacci numbers $F_1$ and $F_2$ are both equal to 1. The following Fibonacci numbers are defined according to the rule
\begin{equation*} F_{n} = F_{n-1} + F_{n-2}, \end{equation*}for $n \geq 3$. Create a list of the first 100 Fibonacci numbers. Print the list.
Hint. Read about negative indexing on page 35 of PCC.
# Write your code here
fib = [1, 1]
for i in range(0, 98):
fib.append(fib[-1] + fib[-2])
print(fib)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 20365011074, 32951280099, 53316291173, 86267571272, 139583862445, 225851433717, 365435296162, 591286729879, 956722026041, 1548008755920, 2504730781961, 4052739537881, 6557470319842, 10610209857723, 17167680177565, 27777890035288, 44945570212853, 72723460248141, 117669030460994, 190392490709135, 308061521170129, 498454011879264, 806515533049393, 1304969544928657, 2111485077978050, 3416454622906707, 5527939700884757, 8944394323791464, 14472334024676221, 23416728348467685, 37889062373143906, 61305790721611591, 99194853094755497, 160500643816367088, 259695496911122585, 420196140727489673, 679891637638612258, 1100087778366101931, 1779979416004714189, 2880067194370816120, 4660046610375530309, 7540113804746346429, 12200160415121876738, 19740274219868223167, 31940434634990099905, 51680708854858323072, 83621143489848422977, 135301852344706746049, 218922995834555169026, 354224848179261915075]