Skip to content
Snippets Groups Projects
Commit 998a8a33 authored by GURMAIL SINGH's avatar GURMAIL SINGH
Browse files

Lec11 update

parent 93c8404c
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:5117857a tags:
# Announcements - Friday
* Download files for today's lecture
* Quiz 3 due today
* P4 Bad Link
* [Thank You](https://docs.google.com/forms/d/e/1FAIpQLSe0Zi6JFbxPIEVr7u1DJykuel-qSi7U0sBp2iR0gi6R_CArgw/viewform)
* [Regrade request procedure](https://piazza.com/class/ld8bqui1lgeas/post/105)
* Exam 1
* Number 2 pencil
* Room assignment via Canvas Message (before Tuesday)
* [Exam 1 Conflict Form](https://docs.google.com/forms/d/e/1FAIpQLScKmey733tOjLfJ2q13Np76w_4o6cFcGVyNqWZmseZH0KNp2w/viewform)
* one page note sheet
* put anything you want on this sheet
* we will keep this sheet - make a copy if you want one
* ID Card and #2 pencil
* General: Wednesday February 22: 5:45 pm
* McBurney: Wednesday Februrary 22 5:30 pm - If you are approved for anything other than extra time and small group testing please fill out the form
* Alternate: Thursday February 23 5:45 pm
* Location will be sent by email on Monday February 20
* Note: Chemistry has an exam at the same time as our Wednesday exam
* Note: Wednesday Evening section
- alternate time 7:30 - 9:00 pm
- please fill out the conflict form to get on the list for the location email
- feel free to revise your conflict form if this time works better for you
* [The best way to study for the exam!!!](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-lecture-material/-/tree/main/s23/old_exams/exam1)
%% Cell type:markdown id:1fd5544f tags:
# Iteration 2
## Readings:
- Chapter 2 of Sweigart book
- Chapter 6.4 of Python for Everybody
%% Cell type:code id:e15b9d08 tags:
``` python
import math
```
%% Cell type:markdown id:ebce36a5 tags:
## Learning Objectives
- 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:markdown id:8f91daea 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:code id:5ec2099a 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:18f5a22c 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:daca8575 tags:
``` python
def has_prime(start, end):
found_prime = False
num = start
while num <= end:
if is_prime(num):
print(num)
found_prime = True
# As soon as you find the first prime, your work
# here is done, hence the break out of the loop!
break
num += 1
return found_prime
```
%% Cell type:code id:0f7bd5ca tags:
``` python
has_prime(14, 16)
```
%% Output
False
%% Cell type:code id:4fd676f3 tags:
``` python
has_prime(1000000, 1001000)
```
%% Output
1000003
True
%% Cell type:markdown id:dfc74fed 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:e90b47b5 tags:
``` python
total = 0 # sum
count = 0
while True:
#Handle "q" input for quitting
age = input("Enter an age [0-100]: ")
if age == "q":
break
age = float(age)
if age < 0 or age > 100:
print("Bad input!")
continue
total += age
count += 1
print("Average age of user so far is: ", total / count)
```
%% Output
Enter an age [0-100]: 10
Average age of user so far is: 10.0
Enter an age [0-100]: 20
Average age of user so far is: 15.0
Enter an age [0-100]: 102
Bad input!
Enter an age [0-100]: q
%% Cell type:markdown id:8b037e4f tags:
### After lecture
%% Cell type:markdown id:bf87a5ac tags:
How many times is the *while loop condition line* executed?
%% Cell type:code id:cb6bb684 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:4def9307 tags:
Refactor the below function.
%% Cell type:code id:9421ad49 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
```
%% Output
False
True
False
True
False
%% Cell type:code id:21951d05 tags:
``` python
def is_between_v2(a, b, c):
return a < b < c or c < b < a
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
```
%% Output
False
True
False
True
False
%% Cell type:markdown id:0f71dc12 tags:
Trace the output without using Python interpreter
%% Cell type:code id:b942d01f 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:7743e03b 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:markdown id:e6f081e5 tags:
# Announcements - Friday
* Download files for today's lecture
* Quiz 3 due today
* P4 Bad Link
* [Thank You](https://docs.google.com/forms/d/e/1FAIpQLSe0Zi6JFbxPIEVr7u1DJykuel-qSi7U0sBp2iR0gi6R_CArgw/viewform)
* [Regrade request procedure](https://piazza.com/class/ld8bqui1lgeas/post/105)
* Exam 1
* Number 2 pencil
* Room assignment via Canvas Message (before Tuesday)
* [Exam 1 Conflict Form](https://docs.google.com/forms/d/e/1FAIpQLScKmey733tOjLfJ2q13Np76w_4o6cFcGVyNqWZmseZH0KNp2w/viewform)
* one page note sheet
* put anything you want on this sheet
* we will keep this sheet - make a copy if you want one
* ID Card and #2 pencil
* General: Wednesday February 22: 5:45 pm
* McBurney: Wednesday Februrary 22 5:30 pm - If you are approved for anything other than extra time and small group testing please fill out the form
* Alternate: Thursday February 23 5:45 pm
* Location will be sent by email on Monday February 20
* Note: Chemistry has an exam at the same time as our Wednesday exam
* Note: Wednesday Evening section
- alternate time 7:30 - 9:00 pm
- please fill out the conflict form to get on the list for the location email
- feel free to revise your conflict form if this time works better for you
* [The best way to study for the exam!!!](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-lecture-material/-/tree/main/s23/old_exams/exam1)
%% Cell type:markdown id:cce4a7bf tags:
# Iteration 2
## Readings:
- Chapter 2 of Sweigart book
- Chapter 6.4 of Python for Everybody
%% Cell type:code id:7693263d tags:
``` python
import math
```
%% Cell type:markdown id:0b7e0914 tags:
## Learning Objectives
- 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:markdown id:06b520a0 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:code id:8067fa3e 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 = ???
while ???:
# check if num is divisible by divisor
if num % divisor == ???:
return ???
divisor ???
return ???
```
%% Cell type:code id:2e3d3f29 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:9a28c726 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:5cde0776 tags:
``` python
has_prime(14, 16)
```
%% Cell type:code id:3a5be934 tags:
``` python
has_prime(1000000, 1001000)
```
%% Cell type:markdown id:12c14f3b 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:ef8d6e0b 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:944cc596 tags:
### After lecture
%% Cell type:markdown id:0820ba66 tags:
How many times is the *while loop condition line* executed?
%% Cell type:code id:c3c14b7b 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:7cf19523 tags:
Refactor the below function.
%% Cell type:code id:a313a32f 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:7fd82ae9 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:ca9037f7 tags:
Trace the output without using Python interpreter
%% Cell type:code id:ec8b1b32 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:74060bc4 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:markdown id:1fd5544f tags:
%% Cell type:markdown id:e6f081e5 tags:
# Announcements - Friday
* Download files for today's lecture
* Quiz 3 due today
* P4 Bad Link
* [Thank You](https://docs.google.com/forms/d/e/1FAIpQLSe0Zi6JFbxPIEVr7u1DJykuel-qSi7U0sBp2iR0gi6R_CArgw/viewform)
* [Regrade request procedure](https://piazza.com/class/ld8bqui1lgeas/post/105)
* Exam 1
* Number 2 pencil
* Room assignment via Canvas Message (before Tuesday)
* [Exam 1 Conflict Form](https://docs.google.com/forms/d/e/1FAIpQLScKmey733tOjLfJ2q13Np76w_4o6cFcGVyNqWZmseZH0KNp2w/viewform)
* one page note sheet
* put anything you want on this sheet
* we will keep this sheet - make a copy if you want one
* ID Card and #2 pencil
* General: Wednesday February 22: 5:45 pm
* McBurney: Wednesday Februrary 22 5:30 pm - If you are approved for anything other than extra time and small group testing please fill out the form
* Alternate: Thursday February 23 5:45 pm
* Location will be sent by email on Monday February 20
* Note: Chemistry has an exam at the same time as our Wednesday exam
* Note: Wednesday Evening section
- alternate time 7:30 - 9:00 pm
- please fill out the conflict form to get on the list for the location email
- feel free to revise your conflict form if this time works better for you
* [The best way to study for the exam!!!](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-lecture-material/-/tree/main/s23/old_exams/exam1)
%% Cell type:markdown id:cce4a7bf tags:
# Iteration 2
## Readings:
- Chapter 2 of Sweigart book
- Chapter 6.4 of Python for Everybody
%% Cell type:code id:e15b9d08 tags:
%% Cell type:code id:7693263d tags:
``` python
import math
```
%% Cell type:markdown id:ebce36a5 tags:
%% Cell type:markdown id:0b7e0914 tags:
## Learning Objectives
- 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:markdown id:8f91daea tags:
%% Cell type:markdown id:06b520a0 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:code id:5ec2099a tags:
%% Cell type:code id:8067fa3e 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):
divisor = ???
while ???:
# check if num is divisible by divisor
if num % divisor == 0:
return False
divisor += 1
if num % divisor == ???:
return ???
divisor ???
return True
return ???
```
%% Cell type:code id:18f5a22c tags:
%% Cell type:code id:2e3d3f29 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:daca8575 tags:
%% Cell type:code id:9a28c726 tags:
``` python
def has_prime(start, end):
found_prime = False
num = start
while num <= end:
if is_prime(num):
print(num)
found_prime = True
# As soon as you find the first prime, your work
# here is done, hence the break out of the loop!
break
num += 1
return found_prime
# 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:0f7bd5ca tags:
%% Cell type:code id:5cde0776 tags:
``` python
has_prime(14, 16)
```
%% Output
False
%% Cell type:code id:4fd676f3 tags:
%% Cell type:code id:3a5be934 tags:
``` python
has_prime(1000000, 1001000)
```
%% Output
1000003
True
%% Cell type:markdown id:dfc74fed tags:
%% Cell type:markdown id:12c14f3b 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:e90b47b5 tags:
%% Cell type:code id:ef8d6e0b tags:
``` python
total = 0 # sum
count = 0
# TODO: write an infinite loop using while
while True:
#Handle "q" input for quitting
age = input("Enter an age [0-100]: ")
if age == "q":
break
# TODO: get user input for age
age = float(age)
# Goal: to compute running average
# It is easy to keep track of total and number of user
# inputs to compute running average
if age < 0 or age > 100:
print("Bad input!")
continue
# TODO: discuss what is acceptable range for age
# What is the guinness world record for oldest person?
total += age
count += 1
# 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
print("Average age of user so far is: ", total / count)
```
# 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
%% Output
Enter an age [0-100]: 10
Average age of user so far is: 10.0
Enter an age [0-100]: 20
Average age of user so far is: 15.0
Enter an age [0-100]: 102
Bad input!
Enter an age [0-100]: q
# 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:8b037e4f tags:
%% Cell type:markdown id:944cc596 tags:
### After lecture
%% Cell type:markdown id:bf87a5ac tags:
%% Cell type:markdown id:0820ba66 tags:
How many times is the *while loop condition line* executed?
%% Cell type:code id:cb6bb684 tags:
%% Cell type:code id:c3c14b7b 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:4def9307 tags:
%% Cell type:markdown id:7cf19523 tags:
Refactor the below function.
%% Cell type:code id:9421ad49 tags:
%% Cell type:code id:a313a32f 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
```
%% Output
False
True
False
True
False
%% Cell type:code id:21951d05 tags:
%% Cell type:code id:7fd82ae9 tags:
``` python
def is_between_v2(a, b, c):
return a < b < c or c < b < a
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
```
%% Output
False
True
False
True
False
%% Cell type:markdown id:0f71dc12 tags:
%% Cell type:markdown id:ca9037f7 tags:
Trace the output without using Python interpreter
%% Cell type:code id:b942d01f tags:
%% Cell type:code id:ec8b1b32 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:7743e03b tags:
%% Cell type:code id:74060bc4 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
```
......
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