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

lec 6 materials

parent 6f136e8a
No related branches found
No related tags found
No related merge requests found
File added
%% Cell type:markdown id:dd1c3a1b tags:
# Iteration 1
## Readings:
- Chapter 7 of Think Python
- Chapter 6.1 to 6.3 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
%% 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 = ???
# TODO: copy start into another variable
remaining = ???
while ???: # 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 -= ???
# 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
# TODO: print "BEEP BEEP BEEP ..." (10 BEEPS) without typing BEEP 10 times
# What string operator can you use here?
# wake up call
```
%% 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)
```
%% Cell type:code id:e3f01e6f tags:
``` python
for i in range(5, 10): # two arguments -> produces 5, 6, 7, 8, and 9
print(i)
```
%% Cell type:code id:b37a6842 tags:
``` python
# TODO: write a for loop to iterate over the numbers 2 to 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!")
```
%% 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
```
%% 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?
```
%% 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))
```
%% 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
# 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
print("Best x:", best_x)
print("Best y:", best_y)
```
%% 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 ???:
# check if num is divisible by divisor
if num % divisor == 0:
return False
divisor ???
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))
```
%% 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
```
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