Skip to content
Snippets Groups Projects
Commit 2b6e7ebf authored by LOUIS TYRRELL OLIPHANT's avatar LOUIS TYRRELL OLIPHANT
Browse files

added lec 10 iterations 1

parent 5301525e
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
## Warmup
%% Cell type:code id: tags:
``` python
# Warmup 1: Call can_serve different 3 times: use a positional argument, keyword argument, and default argument.
def can_serve(age=21):
if(age >= 18):
if (age <= 25):
return True
else:
return False
else:
return False
```
%% Cell type:code id: tags:
``` python
# Warmup 2: Refactor the can_serve function.
# e.g.: Write it another way, keeping the same behavior
# Use the same print statements your wrote above to test it.
def refactor_can_serve(age=21):
pass
```
%% Cell type:code id: tags:
``` python
# Warmup 3
# Consider the following code
def refactor(x,y):
if x:
return True
elif y:
return True
else:
return False
print(refactor(True, False))
print(refactor(False, True))
print(refactor(True, True))
print(refactor(False, False))
# what is the best way to refactor the body of the function ?
# A. return x and y
# B. return x or y
# C. return x != y
# D. return x == y
```
%% Cell type:markdown id: tags:
## Reminder
- Conditionals can contain entire blocks of code, including **nested conditionals**
- It is common after getting code to work as intended to **refactor** the code to have the same behavior but to be more readable or execute faster.
%% Cell type:markdown id: tags:
# Iteration
## Readings
* [Downey Ch 7](https://greenteapress.com/thinkpython2/html/thinkpython2008.html)
* [Python for Everybody, 6.1 - 6.3](https://runestone.academy/ns/books/published/py4e-int/iterations/toctree.html)
## Learning Objectives
After this lecture you will be able to...
* Implement an iterative algorithm using a while loop
- example: printing / counting
- example: validating user input
- example: performing an iterative calculation
* 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:markdown id: tags:
## While Loop Syntax
The `while` loop has the following syntax:
```python
while CONDITION:
#code to be executed if CONDITION is True (Body of loop)
#code after while loop
```
If `CONDITION` is true then the indented block of code will be executed and flow-of-control will loop back up to the `CONDITION` again to check its value. If it remains true, the indented block of code will be executed again. This process will repeat indefinitely. If the `CONDITION` is false the indented block of code will be skipped and the first line after the indented block will be executed.
Try the example in the cell below and visualize it running using the debugger or in [the python tutor](https://pythontutor.com/render.html#code=n%20%3D%200%0Awhile%20n%20%3C%2010%3A%0A%20%20%20%20print%28n%29%0A%20%20%20%20n%20%2B%3D%201%0Aprint%28'Done!'%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false).
In addition, we will be looking at the [slides](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-lecture-material/-/blob/main/s24/Common/10_Iteration-1/10_Iteration-1.pdf) that compare the **if statement** and the **while loop**. Their syntax is very similar but their flow of control is different. With an if-statement, the indented block of code will run at most once. With a while-loop, the indented block may run over and over until the `CONDITION` is false.
%% Cell type:code id: tags:
``` python
# Example : Use the debugger to trace the execution of this code
n = 0
while n < 10:
print(n)
n += 1
print('Done!')
```
%% Cell type:markdown id: tags:
### Example -- Counting
When working with loops there are two common mistakes that are made:
* **off-by-one** -- having the wrong logic that executes the loop once too often or once less than it should.
* **infinite loop** -- forgetting to include code in the body that will make sure that the condition will eventually become false.
Follow along to see these common mistakes and the debugging techniques that you can use to find and fix these mistakes.
%% Cell type:code id: tags:
``` python
# Example: Countdown Timer
# The code should prompt for a number, loop from that number down to 1 then print blast off
from time import sleep
count = 0
count = input("Enter in a time to countdown from: ")
count = int(count)
# This loop handles the countdown
while count >= 0:
print(count)
sleep(1)
print("Blast Off!!")
```
%% Cell type:markdown id: tags:
### You Try
**Example: Prime Numbers**
A prime number, x, is a positive integer greater than 1 that is only divisible by itself and 1. If a number is divisible by any other integers then it is not prime. Let's write a function that checks if a number is prime. We can do this by trying to divide it by all numbers from 2 to x-1.
Finish writing the `is_prime()` function below and test it by calling different numbers that are prime and that are not prime.
Some primes: 2, 7, 19, 29<br>
Non-primes: 6, 15, 30
%% Cell type:code id: tags:
``` python
# Example: write a function to determine if an integer is prime
import math
def is_prime(x):
""" returns True if x is prime, false otherwise. Assumes x is an int"""
# first let's make sure it is >1, otherwise return False
if x <= 1:
return False
# Now let's try dividing x by all numbers between 2 and x-1. As soon as you discover that it is divisible by
# any of these numbers you know it is not prime so return False
# if you finish the entire loop and never returned False then it must be prime so return True
divisor = 2
while divisor <= x-1:
# TODO: Finish function
pass
##TODO: call your function and see if it returns the proper value
```
%% Cell type:markdown id: tags:
Now that you have a working `is_prime()` function, let's use it to print out all the primes between 1 and 100.
Write code in the cell below to loop through all values from 1 to 100 and call the is_prime() function on each of these values. Print those values that are prime.
%% Cell type:code id: tags:
``` python
# Example: Print the prime numbers between 1 and 100
# TODO: Write Code here
```
%% Cell type:markdown id: tags:
### Example -- Validating User Input
One common use of a loop is to check user input. You setup a loop that repeats until a user types in a proper value. Take a look at the code below to see one way to do this.
%% Cell type:code id: tags:
``` python
## A function which gets an integer in a specific range from the user
def get_int(low=1,high=10):
repeat = True
while repeat:
num = int(input("Enter an integer between "+str(low)+" and "+str(high)+":"))
if num<low or num>high:
print("invalid input")
else:
repeat = False
return num
val = get_int()
print("You entered",val)
```
%% Cell type:markdown id: tags:
### You Try
The code in the cell below allows you to guess a random number between 1 and 100. Run the code and see how it works.
Now modify the code to keep track of how many guesses it takes to discover the hidden number and after the number is guessed tell them how many guesses it took.
%% Cell type:code id: tags:
``` python
from random import randint
low = 1
high = 100
hidden_number = randint(low,high)
guessed_number = False
##TODO: Create a count variable and start it at 0
while not guessed_number:
print("Guess my number.")
guess = get_int(low,high)
##TODO: A guess just happened so increment the count variable
if guess == hidden_number:
print("You guessed it!")
##TODO: print out how many guesses it took
guessed_number = True
else:
print("That is not it. Try again.")
if guess < hidden_number:
print("you are too low")
else:
print("you are too high")
```
%% Cell type:markdown id: tags:
### You Try
Finish writing the code to get 10 test scores (between 0 and 100) and print out the average score. Use the `get_int()` function.
%% Cell type:code id: tags:
``` python
total = 0
count = 0
while ##TODO -- Write the CONDITION so loop runs 10 times:
test_score = get_int(0,100)
##TODO update total and count
#TODO print out the average of total/count
```
%% Cell type:markdown id: tags:
## Example -- Finding the Maximum Value
One way of looking for the maximum value of a function is to scan across a range of input values and see what the output from the function is and keeping the largest value seen. The function $5-(x-2)^2$ is defined in the function in the cell below. Run the cell so it is defined, then test it by printing input values and the associated output values in the cell below that.
%% Cell type:markdown id: tags:
![graph.png](attachment:graph.png)
%% Cell type:code id: tags:
``` python
# Example 3a: define the function
def f(x):
return 5 - (x-2)**2
```
%% Cell type:code id: tags:
``` python
# ... and test it!
print("x , y")
print(-1,",",f(-1))
print(0,",",f(0))
print(3,",",f(3))
print(6,",",f(6))
```
%% Cell type:code id: tags:
``` python
# Example: Now write code to iterate over values from start_x to end_x in steps of delta_x
# printing out the x and y values
start_x = 0
end_x = 5
delta_x = 0.1
# TODO: Write Code Here
current_x = start_x
while current_x <= end_x:
print(current_x,f(current_x))
current_x += delta_x
```
%% Cell type:markdown id: tags:
### You Try
Now write the code again, but this time keep track of the highest y value seen and just print out the x and y values for this maximum.
%% Cell type:code id: tags:
``` python
# TODO: finish this code
start_x = 0
end_x = 5
delta_x = 0.1
# TODO: Write Code Here
```
%% Cell type:markdown id: tags:
## Summary
You learned the syntax for writing a **while** loop and you practiced using while loops to count, validate user input and perform some mathematical computations.
This diff is collapsed.
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