Skip to content
Snippets Groups Projects
Commit d15e2b06 authored by Anna Meyer's avatar Anna Meyer
Browse files

lec 6 notes

parent 8e49a5fa
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:dd1c3a1b tags:
# Iteration
## Readings:
### For Friday
- Chapter 7 of Think Python
- Chapter 6.1 to 6.3 of Python for Everybody
### For Monday
- Chapter 2 of Sweigart book
- Chapter 6.4 of Python for Everybody
%% Cell type:markdown id:595d2e5b tags:
## Learning Objectives:
- Implement an iterative algorithm using a `while` loop, for
- printing / counting
- validating user input
- performing an iterative calculation
- printing character art
- Trace iterative algorithms and determine their output
- Recognize common `while` loop errors
- Infinite loops (when unintentional)
- Off-by-one mistakes in the loop control variable
- Read and trace through Python code containing nested loops.
- Read and trace through Python code using `break` or `continue` in a `while` loop
- Determine the effect of break and continue in nested loops
%% Cell type:code id:c30a8ea2 tags:
``` python
# import statements
import time
import math
```
%% Cell type:markdown id:f113fc7b tags:
### Example 0: Simple countdowns
%% Cell type:markdown id:73959e77 tags:
**How to termination infinite loop in:**
- jupyter: Kernel > Interrupt (fix and then re-run)
- script mode / interactive mode: Ctrl + C (Kill signal)
%% Cell type:code id:cb8de263 tags:
``` python
#TODO: Copy/paste this example into PythonTutor
#Count from 0 to 3, printing each number
count = 0
while count <= 3:
print(count)
count += 1
```
%% Cell type:code id:23dbc9da tags:
``` python
#TODO: Copy/paste this example into PythonTutor
#Count from 3 to -3, printing each number
count = 3
while count >= -3:
print(count)
count -= 1
```
%% Cell type:markdown id:115e8742 tags:
### Example 1: Countdown timer alarm
%% Cell type:code id:42f4a48f tags:
``` python
# TODO: use input function to get user input for number of seconds
start = input("How many seconds?")
# TODO: copy start into another variable
remaining = int(start)
while remaining >= 1: # TODO: iterate from start to 1
print(remaining, "seconds left")
# TODO: update loop control variable's value to make progress towards terminating
# the loop, that is turning loop condition to False
remaining -= 1
# TODO: now run the cell to see the output. Didn't it go too fast?
# TODO: call time module sleep function, by passing 1 as argument
time.sleep(1)
# TODO: print "BEEP BEEP BEEP ..." (10 BEEPS) without typing BEEP 10 times
# What string operator can you use here?
print("BEEP " * 10)
# wake up call
```
%% Output
How many seconds?5
5 seconds left
4 seconds left
3 seconds left
2 seconds left
1 seconds left
BEEP BEEP BEEP BEEP BEEP BEEP BEEP BEEP BEEP BEEP
%% Cell type:markdown id:d54200ad tags:
## `for` loop
- another kind of loop
- does not require initialization of loop control variable outside the loop
- loop statement itself creates the loop control variable
- keywords `for` and `in`
### range built-in function
- accepts a single integer argument and produces a sequence of numbers from 0 to argument - 1, that is argument is exclusive
- accepts two integer arguments and produces a sequence of numbers from start (argument1) to end (argument2) - 1
%% Cell type:code id:43776615 tags:
``` python
for i in range(5): # single arugment -> produces 0, 1, 2, 3, and 4
print(i)
```
%% Output
0
1
2
3
4
%% Cell type:code id:e3f01e6f tags:
``` python
for i in range(5, 10): # two arguments -> produces 5, 6, 7, 8, and 9
print(i)
```
%% Output
5
6
7
8
9
%% Cell type:code id:b37a6842 tags:
``` python
# TODO: write a for loop to iterate over the numbers 2 to 8
for var in range(2, 9):
print(var)
```
%% Output
2
3
4
5
6
7
8
%% Cell type:markdown id:558e4bed tags:
### Example 2: Print the square of all positive numbers <= 5
First, we show the code for how to do this with a while loop. Then, we'll work together to do the same thing with a for loop.
%% Cell type:code id:5ec1ba4f tags:
``` python
x = 1
while x <= 5:
print(str(x) + " squared is:")
print(str (x ** 2))
x += 1
print("all done!")
print("x is ",str(x))
```
%% Output
1 squared is:
1
2 squared is:
4
3 squared is:
9
4 squared is:
16
5 squared is:
25
all done!
x is 6
%% Cell type:code id:1de3a188 tags:
``` python
# TODO write a function using a for loop that prints the square of all positive numbers <= 5
# the output should be identical to the output of the cell above
# x = 1 # we need to initialize x for a while loop, but a for loop automatically
# initializes x
for x in range(1, 6):
print(str(x) + " squared is:")
print(str (x ** 2))
print("all done!")
```
%% Output
1 squared is:
1
2 squared is:
4
3 squared is:
9
4 squared is:
16
5 squared is:
25
all done!
%% Cell type:code id:9df8c834 tags:
``` python
# TODO what value does x have after the for loop finishes? What about after the while loop finishes?
print("after for, x is ", str(x))
```
%% Output
after for, x is 5
%% Cell type:markdown id:cdc66ffa tags:
### Example 3: Find the max value of a function on an interval
<div>
<img src="attachment:Curve_peak.png" width="600"/>
</div>
%% Cell type:code id:2ec27141 tags:
``` python
def f(x):
return 5 - (x - 2) ** 2
print(f(1))
```
%% Output
4
%% Cell type:code id:0098b6aa tags:
``` python
# TODO: for what value of x will f(x) produce the maximum y value?
print(f(???))
```
%% Cell type:code id:27298992 tags:
``` python
# Goal: find the x that maximizes the y = f(x)
# Let's try the values from -5 to 5
# Goal: after the loop, best_x and best_y should contain just that
best_x = 0
best_y = -99999999
# Try out increasing increments, make sure to comment the other increment
# delta_x = 1
# delta_x = 0.1
delta_x = 0.01
# delta_x = 0.001
# this is fine, but only lets us check integers
# for x in range(-5, 6):
# fx = f(x)
# if fx > best_y:
# best_x = x
# best_y = fx
x = -5
while x <= 5:
fx = f(x)
if fx > best_y:
best_x = x
best_y = fx
x += delta_x
print("Best x:", best_x)
print("Best y:", best_y)
```
%% Output
Best x: 1.9999999999999392
Best y: 5.0
%% Cell type:markdown id:249f2aa7 tags:
### Example 4: Integration (Riemann Sum)
<div>
<img src="attachment:ReimannSum.png" width="600"/>
</div>
%% Cell type:code id:96b98336 tags:
``` python
# Let's try the values from 1 to 5
start_x = 1
end_x = 5
total_area = 0
current_x = start_x
# Try out increasing values of width, make sure to comment the other width values
# delta_x = 1
delta_x = 0.1
# delta_x = 0.01
# delta_x = 0.001
while current_x <= end_x:
y = ??? # TODO: use f(x) defined previously
rect_area = ???
total_area += ???
current_x += delta_x
print("Area found using approximation is:", total_area)
```
%% Cell type:markdown id:3e8d609b tags:
### Example 5: Find primes
%% Cell type:code id:f2d0c381 tags:
``` python
def is_prime(num):
""" returns True if x is prime, false otherwise. Assumes x is positive"""
# try all divisors from 2 to sqrt(num) to check if num is prime
divisor = 2
while divisor <= math.sqrt(num):
# check if num is divisible by divisor
if num % divisor == 0:
return False
divisor += 1
return True
```
%% Cell type:code id:e7aea11c tags:
``` python
print(is_prime(1))
print(is_prime(2))
print(is_prime(3))
print(is_prime(7))
print(is_prime(16))
print(is_prime(23))
print(is_prime(1000000))
```
%% Output
True
True
True
True
False
True
False
%% Cell type:code id:d26d790c tags:
``` python
print("Prime numbers:")
number = 2
# TODO: comment out this while loop and write equivalent for loop using range
# while number <= 50:
# if is_prime(number):
# print(number, "is prime")
# else:
# print(number, "is not prime")
# number += 1
for number in range(2, 51):
if is_prime(number):
print(number, "is prime")
else:
print(number, "is not prime")
```
%% Output
Prime numbers:
2 is prime
3 is prime
4 is not prime
5 is prime
6 is not prime
7 is prime
8 is not prime
9 is not prime
10 is not prime
11 is prime
12 is not prime
13 is prime
14 is not prime
15 is not prime
16 is not prime
17 is prime
18 is not prime
19 is prime
20 is not prime
21 is not prime
22 is not prime
23 is prime
24 is not prime
25 is not prime
26 is not prime
27 is not prime
28 is not prime
29 is prime
30 is not prime
31 is prime
32 is not prime
33 is not prime
34 is not prime
35 is not prime
36 is not prime
37 is prime
38 is not prime
39 is not prime
40 is not prime
41 is prime
42 is not prime
43 is prime
44 is not prime
45 is not prime
46 is not prime
47 is prime
48 is not prime
49 is not prime
50 is not prime
%% Cell type:markdown id:0f29c848 tags:
## `break` and `continue`
`break` and `continue` are python keywords that let us end loop execution early
%% Cell type:markdown id:9dc76b8a tags:
### `break` example
- `break` enables to terminate execution of a while loop
- typically used with a conditional; that is you break when condition evaluates to `True`
%% Cell type:markdown id:81abdb38 tags:
def is_prime(num):
""" returns True if x is prime, false otherwise.
Assumes x is positive"""
# try all divisors from 2 to sqrt(num) to check if num is prime
divisor = ???
while ???:
# check if num is divisible by divisor
if num % divisor == ???:
return ???
divisor ???
return ???
%% Cell type:code id:e432722e tags:
``` python
print(is_prime(1))
print(is_prime(2))
print(is_prime(3))
print(is_prime(7))
print(is_prime(16))
print(is_prime(23))
print(is_prime(1000000))
```
%% Cell type:code id:c69150ed tags:
``` python
def has_prime(start, end):
# TODO: write a for loop using range, to:
# 1. iterate over every number from start to end
# 2. call is_prime function, to determine if it is prime
# 3. if you find at least one prime, has_prime should
# return True, False otherwise
pass
```
%% Cell type:code id:bd3e2027 tags:
``` python
has_prime(14, 16)
```
%% Cell type:code id:0429022b tags:
``` python
has_prime(1000000, 1001000)
```
%% Cell type:markdown id:32ba3308 tags:
### `continue` example
- `continue` enables to move on to the next iteration of the while loop
- typically used with a conditional; that is you continue when condition evaluates to `True`
%% Cell type:code id:cb569b21 tags:
``` python
# TODO: write an infinite loop using while
# TODO: get user input for age
# Goal: to compute running average
# It is easy to keep track of total and number of user
# inputs to compute running average
# TODO: discuss what is acceptable range for age
# What is the guinness world record for oldest person?
# TODO: discuss where you will initialize variables to keep track
# of total and number of user inputs so far and then type the
# computation lines to compute updated total and running average
# Now, try entering input as a large number outside of your
# acceptable age range. What happens to your average?
# TODO: handle this by writing a conditional and use continue,
# when user enters invalid age
# Finally, how do we terminate the infinite while loop
# Let's accept "q" as user input for termination
# TODO: handle that using another conditional
# Think carefully about where this conditional needs to be in
# terms of control flow
```
%% Cell type:markdown id:eb5bcba6 tags:
## After lecture practice
How many times is the while loop condition line executed?
%% Cell type:code id:1f48b50f tags:
``` python
n = 7
while n >= 5:
print(n)
n -= 1
# Answer is 4.
# Loop condition line always gets executed number of
# iterations + 1 times.
```
%% Cell type:markdown id:bb90cb11 tags:
Refactor the below function.
%% Cell type:code id:47a87068 tags:
``` python
def is_between(a, b, c):
"""Return True if b is between a and c (exclusive),
False otherwise"""
if a < c:
if a < b and b < c:
return True
else:
return False
elif c <= a:
if c < b and b < a:
return True
else:
return False
else:
return False
print(is_between(1, 3, 2)) # False
print(is_between(5, 11, 20)) # True
print(is_between(20, 3, 5)) # False
print(is_between(50, 11, 9)) # True
print(is_between(4, 4, 4)) # False
```
%% Cell type:code id:73f6ad82 tags:
``` python
def is_between_v2(a, b, c):
return ???
print(is_between_v2(1, 3, 2)) # False
print(is_between_v2(5, 11, 20)) # True
print(is_between_v2(20, 3, 5)) # False
print(is_between_v2(50, 11, 9)) # True
print(is_between_v2(4, 4, 4)) # False
```
%% Cell type:markdown id:11a9f3ce tags:
Trace the output without using Python interpreter
%% Cell type:code id:f0cac75c tags:
``` python
x = 1
while x < 5:
y = 1
while y < 10:
print (x * y, "\t", end="")
y += 1
print()
x += 1
```
%% Cell type:code id:eb1dc7f0 tags:
``` python
width = 9
height = 4
symbol = '#'
row = 0
while row < height:
col = 0
if row % 2 == 1:
print(" ", end="")
while col < width:
print(symbol + ' ', end="")
col += 1
# displays just a newline
print() # recall default value for end parameter is "\n"
row += 1
```
%% Cell type:code id:d572d8b0 tags:
``` python
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment