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: %% Cell type:markdown id:1fd5544f tags:
# Iteration 2 # Iteration 2
## Readings: ## Readings:
- Chapter 2 of Sweigart book - Chapter 2 of Sweigart book
- Chapter 6.4 of Python for Everybody - Chapter 6.4 of Python for Everybody
%% Cell type:code id:e15b9d08 tags: %% Cell type:code id:e15b9d08 tags:
``` python ``` python
import math import math
``` ```
%% Cell type:markdown id:ebce36a5 tags: %% Cell type:markdown id:ebce36a5 tags:
## Learning Objectives ## Learning Objectives
- Read and trace through Python code containing nested loops. - Read and trace through Python code containing nested loops.
- Read and trace through Python code using `break` or `continue` in a `while` loop - Read and trace through Python code using `break` or `continue` in a `while` loop
- Determine the effect of break and continue in nested loops - Determine the effect of break and continue in nested loops
%% Cell type:markdown id:8f91daea tags: %% Cell type:markdown id:8f91daea tags:
## `break` example ## `break` example
- `break` enables to terminate execution of a while loop - `break` enables to terminate execution of a while loop
- typically used with a conditional; that is you break when condition evaluates to `True` - typically used with a conditional; that is you break when condition evaluates to `True`
%% Cell type:code id:5ec2099a tags: %% Cell type:code id:5ec2099a tags:
``` python ``` python
def is_prime(num): def is_prime(num):
""" returns True if x is prime, false otherwise. """ returns True if x is prime, false otherwise.
Assumes x is positive""" Assumes x is positive"""
# try all divisors from 2 to sqrt(num) to check if num is prime # try all divisors from 2 to sqrt(num) to check if num is prime
divisor = 2 divisor = 2
while divisor <= math.sqrt(num): while divisor <= math.sqrt(num):
# check if num is divisible by divisor # check if num is divisible by divisor
if num % divisor == 0: if num % divisor == 0:
return False return False
divisor += 1 divisor += 1
return True return True
``` ```
%% Cell type:code id:18f5a22c tags: %% Cell type:code id:18f5a22c tags:
``` python ``` python
print(is_prime(1)) print(is_prime(1))
print(is_prime(2)) print(is_prime(2))
print(is_prime(3)) print(is_prime(3))
print(is_prime(7)) print(is_prime(7))
print(is_prime(16)) print(is_prime(16))
print(is_prime(23)) print(is_prime(23))
print(is_prime(1000000)) print(is_prime(1000000))
``` ```
%% Output %% Output
True True
True True
True True
True True
False False
True True
False False
%% Cell type:code id:daca8575 tags: %% Cell type:code id:daca8575 tags:
``` python ``` python
def has_prime(start, end): def has_prime(start, end):
found_prime = False found_prime = False
num = start num = start
while num <= end: while num <= end:
if is_prime(num): if is_prime(num):
print(num) print(num)
found_prime = True found_prime = True
# As soon as you find the first prime, your work # As soon as you find the first prime, your work
# here is done, hence the break out of the loop! # here is done, hence the break out of the loop!
break break
num += 1 num += 1
return found_prime return found_prime
``` ```
%% Cell type:code id:0f7bd5ca tags: %% Cell type:code id:0f7bd5ca tags:
``` python ``` python
has_prime(14, 16) has_prime(14, 16)
``` ```
%% Output %% Output
False False
%% Cell type:code id:4fd676f3 tags: %% Cell type:code id:4fd676f3 tags:
``` python ``` python
has_prime(1000000, 1001000) has_prime(1000000, 1001000)
``` ```
%% Output %% Output
1000003 1000003
True True
%% Cell type:markdown id:dfc74fed tags: %% Cell type:markdown id:dfc74fed tags:
## `continue` example ## `continue` example
- `continue` enables to move on to the next iteration of the while loop - `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` - typically used with a conditional; that is you continue when condition evaluates to `True`
%% Cell type:code id:e90b47b5 tags: %% Cell type:code id:e90b47b5 tags:
``` python ``` python
total = 0 # sum total = 0 # sum
count = 0 count = 0
while True: while True:
#Handle "q" input for quitting #Handle "q" input for quitting
age = input("Enter an age [0-100]: ") age = input("Enter an age [0-100]: ")
if age == "q": if age == "q":
break break
age = float(age) age = float(age)
if age < 0 or age > 100: if age < 0 or age > 100:
print("Bad input!") print("Bad input!")
continue continue
total += age total += age
count += 1 count += 1
print("Average age of user so far is: ", total / count) print("Average age of user so far is: ", total / count)
``` ```
%% Output %% Output
Enter an age [0-100]: 10 Enter an age [0-100]: 10
Average age of user so far is: 10.0 Average age of user so far is: 10.0
Enter an age [0-100]: 20 Enter an age [0-100]: 20
Average age of user so far is: 15.0 Average age of user so far is: 15.0
Enter an age [0-100]: 102 Enter an age [0-100]: 102
Bad input! Bad input!
Enter an age [0-100]: q Enter an age [0-100]: q
%% Cell type:markdown id:8b037e4f tags: %% Cell type:markdown id:8b037e4f tags:
### After lecture ### After lecture
%% Cell type:markdown id:bf87a5ac tags: %% Cell type:markdown id:bf87a5ac tags:
How many times is the *while loop condition line* executed? How many times is the *while loop condition line* executed?
%% Cell type:code id:cb6bb684 tags: %% Cell type:code id:cb6bb684 tags:
``` python ``` python
n = 7 n = 7
while n >= 5: while n >= 5:
print(n) print(n)
n -= 1 n -= 1
# Answer is 4. # Answer is 4.
# Loop condition line always gets executed number of # Loop condition line always gets executed number of
# iterations + 1 times. # iterations + 1 times.
``` ```
%% Cell type:markdown id:4def9307 tags: %% Cell type:markdown id:4def9307 tags:
Refactor the below function. Refactor the below function.
%% Cell type:code id:9421ad49 tags: %% Cell type:code id:9421ad49 tags:
``` python ``` python
def is_between(a, b, c): def is_between(a, b, c):
"""Return True if b is between a and c (exclusive), """Return True if b is between a and c (exclusive),
False otherwise""" False otherwise"""
if a < c: if a < c:
if a < b and b < c: if a < b and b < c:
return True return True
else: else:
return False return False
elif c <= a: elif c <= a:
if c < b and b < a: if c < b and b < a:
return True return True
else: else:
return False return False
else: else:
return False return False
print(is_between(1, 3, 2)) # False print(is_between(1, 3, 2)) # False
print(is_between(5, 11, 20)) # True print(is_between(5, 11, 20)) # True
print(is_between(20, 3, 5)) # False print(is_between(20, 3, 5)) # False
print(is_between(50, 11, 9)) # True print(is_between(50, 11, 9)) # True
print(is_between(4, 4, 4)) # False print(is_between(4, 4, 4)) # False
``` ```
%% Output %% Output
False False
True True
False False
True True
False False
%% Cell type:code id:21951d05 tags: %% Cell type:code id:21951d05 tags:
``` python ``` python
def is_between_v2(a, b, c): def is_between_v2(a, b, c):
return a < b < c or c < b < a return a < b < c or c < b < a
print(is_between_v2(1, 3, 2)) # False print(is_between_v2(1, 3, 2)) # False
print(is_between_v2(5, 11, 20)) # True print(is_between_v2(5, 11, 20)) # True
print(is_between_v2(20, 3, 5)) # False print(is_between_v2(20, 3, 5)) # False
print(is_between_v2(50, 11, 9)) # True print(is_between_v2(50, 11, 9)) # True
print(is_between_v2(4, 4, 4)) # False print(is_between_v2(4, 4, 4)) # False
``` ```
%% Output %% Output
False False
True True
False False
True True
False False
%% Cell type:markdown id:0f71dc12 tags: %% Cell type:markdown id:0f71dc12 tags:
Trace the output without using Python interpreter Trace the output without using Python interpreter
%% Cell type:code id:b942d01f tags: %% Cell type:code id:b942d01f tags:
``` python ``` python
x = 1 x = 1
while x < 5: while x < 5:
y = 1 y = 1
while y < 10: while y < 10:
print (x * y, "\t", end="") print (x * y, "\t", end="")
y += 1 y += 1
print() print()
x += 1 x += 1
``` ```
%% Cell type:code id:7743e03b tags: %% Cell type:code id:7743e03b tags:
``` python ``` python
width = 9 width = 9
height = 4 height = 4
symbol = '#' symbol = '#'
row = 0 row = 0
while row < height: while row < height:
col = 0 col = 0
if row % 2 == 1: if row % 2 == 1:
print(" ", end="") print(" ", end="")
while col < width: while col < width:
print(symbol + ' ', end="") print(symbol + ' ', end="")
col += 1 col += 1
# displays just a newline # displays just a newline
print() # recall default value for end parameter is "\n" print() # recall default value for end parameter is "\n"
row += 1 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: %% Cell type:markdown id:cce4a7bf tags:
# Iteration 2 # Iteration 2
## Readings: ## Readings:
- Chapter 2 of Sweigart book - Chapter 2 of Sweigart book
- Chapter 6.4 of Python for Everybody - Chapter 6.4 of Python for Everybody
%% Cell type:code id:7693263d tags: %% Cell type:code id:7693263d tags:
``` python ``` python
import math import math
``` ```
%% Cell type:markdown id:0b7e0914 tags: %% Cell type:markdown id:0b7e0914 tags:
## Learning Objectives ## Learning Objectives
- Read and trace through Python code containing nested loops. - Read and trace through Python code containing nested loops.
- Read and trace through Python code using `break` or `continue` in a `while` loop - Read and trace through Python code using `break` or `continue` in a `while` loop
- Determine the effect of break and continue in nested loops - Determine the effect of break and continue in nested loops
%% Cell type:markdown id:06b520a0 tags: %% Cell type:markdown id:06b520a0 tags:
## `break` example ## `break` example
- `break` enables to terminate execution of a while loop - `break` enables to terminate execution of a while loop
- typically used with a conditional; that is you break when condition evaluates to `True` - typically used with a conditional; that is you break when condition evaluates to `True`
%% Cell type:code id:8067fa3e tags: %% Cell type:code id:8067fa3e tags:
``` python ``` python
def is_prime(num): def is_prime(num):
""" returns True if x is prime, false otherwise. """ returns True if x is prime, false otherwise.
Assumes x is positive""" Assumes x is positive"""
# try all divisors from 2 to sqrt(num) to check if num is prime # try all divisors from 2 to sqrt(num) to check if num is prime
divisor = ??? divisor = ???
while ???: while ???:
# check if num is divisible by divisor # check if num is divisible by divisor
if num % divisor == ???: if num % divisor == ???:
return ??? return ???
divisor ??? divisor ???
return ??? return ???
``` ```
%% Cell type:code id:2e3d3f29 tags: %% Cell type:code id:2e3d3f29 tags:
``` python ``` python
print(is_prime(1)) print(is_prime(1))
print(is_prime(2)) print(is_prime(2))
print(is_prime(3)) print(is_prime(3))
print(is_prime(7)) print(is_prime(7))
print(is_prime(16)) print(is_prime(16))
print(is_prime(23)) print(is_prime(23))
print(is_prime(1000000)) print(is_prime(1000000))
``` ```
%% Cell type:code id:9a28c726 tags: %% Cell type:code id:9a28c726 tags:
``` python ``` python
def has_prime(start, end): def has_prime(start, end):
# TODO: write a for loop using range, to: # TODO: write a for loop using range, to:
# 1. iterate over every number from start to end # 1. iterate over every number from start to end
# 2. call is_prime function, to determine if it is prime # 2. call is_prime function, to determine if it is prime
# 3. if you find at least one prime, has_prime should # 3. if you find at least one prime, has_prime should
# return True, False otherwise # return True, False otherwise
pass pass
``` ```
%% Cell type:code id:5cde0776 tags: %% Cell type:code id:5cde0776 tags:
``` python ``` python
has_prime(14, 16) has_prime(14, 16)
``` ```
%% Cell type:code id:3a5be934 tags: %% Cell type:code id:3a5be934 tags:
``` python ``` python
has_prime(1000000, 1001000) has_prime(1000000, 1001000)
``` ```
%% Cell type:markdown id:12c14f3b tags: %% Cell type:markdown id:12c14f3b tags:
## `continue` example ## `continue` example
- `continue` enables to move on to the next iteration of the while loop - `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` - typically used with a conditional; that is you continue when condition evaluates to `True`
%% Cell type:code id:ef8d6e0b tags: %% Cell type:code id:ef8d6e0b tags:
``` python ``` python
# TODO: write an infinite loop using while # TODO: write an infinite loop using while
# TODO: get user input for age # TODO: get user input for age
# Goal: to compute running average # Goal: to compute running average
# It is easy to keep track of total and number of user # It is easy to keep track of total and number of user
# inputs to compute running average # inputs to compute running average
# TODO: discuss what is acceptable range for age # TODO: discuss what is acceptable range for age
# What is the guinness world record for oldest person? # What is the guinness world record for oldest person?
# TODO: discuss where you will initialize variables to keep track # TODO: discuss where you will initialize variables to keep track
# of total and number of user inputs so far and then type the # of total and number of user inputs so far and then type the
# computation lines to compute updated total and running average # computation lines to compute updated total and running average
# Now, try entering input as a large number outside of your # Now, try entering input as a large number outside of your
# acceptable age range. What happens to your average? # acceptable age range. What happens to your average?
# TODO: handle this by writing a conditional and use continue, # TODO: handle this by writing a conditional and use continue,
# when user enters invalid age # when user enters invalid age
# Finally, how do we terminate the infinite while loop # Finally, how do we terminate the infinite while loop
# Let's accept "q" as user input for termination # Let's accept "q" as user input for termination
# TODO: handle that using another conditional # TODO: handle that using another conditional
# Think carefully about where this conditional needs to be in # Think carefully about where this conditional needs to be in
# terms of control flow # terms of control flow
``` ```
%% Cell type:markdown id:944cc596 tags: %% Cell type:markdown id:944cc596 tags:
### After lecture ### After lecture
%% Cell type:markdown id:0820ba66 tags: %% Cell type:markdown id:0820ba66 tags:
How many times is the *while loop condition line* executed? How many times is the *while loop condition line* executed?
%% Cell type:code id:c3c14b7b tags: %% Cell type:code id:c3c14b7b tags:
``` python ``` python
n = 7 n = 7
while n >= 5: while n >= 5:
print(n) print(n)
n -= 1 n -= 1
# Answer is 4. # Answer is 4.
# Loop condition line always gets executed number of # Loop condition line always gets executed number of
# iterations + 1 times. # iterations + 1 times.
``` ```
%% Cell type:markdown id:7cf19523 tags: %% Cell type:markdown id:7cf19523 tags:
Refactor the below function. Refactor the below function.
%% Cell type:code id:a313a32f tags: %% Cell type:code id:a313a32f tags:
``` python ``` python
def is_between(a, b, c): def is_between(a, b, c):
"""Return True if b is between a and c (exclusive), """Return True if b is between a and c (exclusive),
False otherwise""" False otherwise"""
if a < c: if a < c:
if a < b and b < c: if a < b and b < c:
return True return True
else: else:
return False return False
elif c <= a: elif c <= a:
if c < b and b < a: if c < b and b < a:
return True return True
else: else:
return False return False
else: else:
return False return False
print(is_between(1, 3, 2)) # False print(is_between(1, 3, 2)) # False
print(is_between(5, 11, 20)) # True print(is_between(5, 11, 20)) # True
print(is_between(20, 3, 5)) # False print(is_between(20, 3, 5)) # False
print(is_between(50, 11, 9)) # True print(is_between(50, 11, 9)) # True
print(is_between(4, 4, 4)) # False print(is_between(4, 4, 4)) # False
``` ```
%% Cell type:code id:7fd82ae9 tags: %% Cell type:code id:7fd82ae9 tags:
``` python ``` python
def is_between_v2(a, b, c): def is_between_v2(a, b, c):
return ??? return ???
print(is_between_v2(1, 3, 2)) # False print(is_between_v2(1, 3, 2)) # False
print(is_between_v2(5, 11, 20)) # True print(is_between_v2(5, 11, 20)) # True
print(is_between_v2(20, 3, 5)) # False print(is_between_v2(20, 3, 5)) # False
print(is_between_v2(50, 11, 9)) # True print(is_between_v2(50, 11, 9)) # True
print(is_between_v2(4, 4, 4)) # False print(is_between_v2(4, 4, 4)) # False
``` ```
%% Cell type:markdown id:ca9037f7 tags: %% Cell type:markdown id:ca9037f7 tags:
Trace the output without using Python interpreter Trace the output without using Python interpreter
%% Cell type:code id:ec8b1b32 tags: %% Cell type:code id:ec8b1b32 tags:
``` python ``` python
x = 1 x = 1
while x < 5: while x < 5:
y = 1 y = 1
while y < 10: while y < 10:
print (x * y, "\t", end="") print (x * y, "\t", end="")
y += 1 y += 1
print() print()
x += 1 x += 1
``` ```
%% Cell type:code id:74060bc4 tags: %% Cell type:code id:74060bc4 tags:
``` python ``` python
width = 9 width = 9
height = 4 height = 4
symbol = '#' symbol = '#'
row = 0 row = 0
while row < height: while row < height:
col = 0 col = 0
if row % 2 == 1: if row % 2 == 1:
print(" ", end="") print(" ", end="")
while col < width: while col < width:
print(symbol + ' ', end="") print(symbol + ' ', end="")
col += 1 col += 1
# displays just a newline # displays just a newline
print() # recall default value for end parameter is "\n" print() # recall default value for end parameter is "\n"
row += 1 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 # Iteration 2
## Readings: ## Readings:
- Chapter 2 of Sweigart book - Chapter 2 of Sweigart book
- Chapter 6.4 of Python for Everybody - Chapter 6.4 of Python for Everybody
%% Cell type:code id:e15b9d08 tags: %% Cell type:code id:7693263d tags:
``` python ``` python
import math import math
``` ```
%% Cell type:markdown id:ebce36a5 tags: %% Cell type:markdown id:0b7e0914 tags:
## Learning Objectives ## Learning Objectives
- Read and trace through Python code containing nested loops. - Read and trace through Python code containing nested loops.
- Read and trace through Python code using `break` or `continue` in a `while` loop - Read and trace through Python code using `break` or `continue` in a `while` loop
- Determine the effect of break and continue in nested loops - 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` example
- `break` enables to terminate execution of a while loop - `break` enables to terminate execution of a while loop
- typically used with a conditional; that is you break when condition evaluates to `True` - 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 ``` python
def is_prime(num): def is_prime(num):
""" returns True if x is prime, false otherwise. """ returns True if x is prime, false otherwise.
Assumes x is positive""" Assumes x is positive"""
# try all divisors from 2 to sqrt(num) to check if num is prime # try all divisors from 2 to sqrt(num) to check if num is prime
divisor = 2 divisor = ???
while divisor <= math.sqrt(num): while ???:
# check if num is divisible by divisor # check if num is divisible by divisor
if num % divisor == 0: if num % divisor == ???:
return False return ???
divisor += 1 divisor ???
return True return ???
``` ```
%% Cell type:code id:18f5a22c tags: %% Cell type:code id:2e3d3f29 tags:
``` python ``` python
print(is_prime(1)) print(is_prime(1))
print(is_prime(2)) print(is_prime(2))
print(is_prime(3)) print(is_prime(3))
print(is_prime(7)) print(is_prime(7))
print(is_prime(16)) print(is_prime(16))
print(is_prime(23)) print(is_prime(23))
print(is_prime(1000000)) print(is_prime(1000000))
``` ```
%% Output %% Cell type:code id:9a28c726 tags:
True
True
True
True
False
True
False
%% Cell type:code id:daca8575 tags:
``` python ``` python
def has_prime(start, end): def has_prime(start, end):
found_prime = False # TODO: write a for loop using range, to:
num = start # 1. iterate over every number from start to end
while num <= end: # 2. call is_prime function, to determine if it is prime
if is_prime(num): # 3. if you find at least one prime, has_prime should
print(num) # return True, False otherwise
found_prime = True pass
# 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: %% Cell type:code id:5cde0776 tags:
``` python ``` python
has_prime(14, 16) has_prime(14, 16)
``` ```
%% Output %% Cell type:code id:3a5be934 tags:
False
%% Cell type:code id:4fd676f3 tags:
``` python ``` python
has_prime(1000000, 1001000) has_prime(1000000, 1001000)
``` ```
%% Output %% Cell type:markdown id:12c14f3b tags:
1000003
True
%% Cell type:markdown id:dfc74fed tags:
## `continue` example ## `continue` example
- `continue` enables to move on to the next iteration of the while loop - `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` - 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 ``` python
total = 0 # sum # TODO: write an infinite loop using while
count = 0
while True: # TODO: get user input for age
#Handle "q" input for quitting
age = input("Enter an age [0-100]: ")
if age == "q":
break
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: # TODO: discuss what is acceptable range for age
print("Bad input!") # What is the guinness world record for oldest person?
continue
total += age # TODO: discuss where you will initialize variables to keep track
count += 1 # 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 # Finally, how do we terminate the infinite while loop
# Let's accept "q" as user input for termination
Enter an age [0-100]: 10 # TODO: handle that using another conditional
Average age of user so far is: 10.0 # Think carefully about where this conditional needs to be in
Enter an age [0-100]: 20 # terms of control flow
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: %% Cell type:markdown id:944cc596 tags:
### After lecture ### After lecture
%% Cell type:markdown id:bf87a5ac tags: %% Cell type:markdown id:0820ba66 tags:
How many times is the *while loop condition line* executed? How many times is the *while loop condition line* executed?
%% Cell type:code id:cb6bb684 tags: %% Cell type:code id:c3c14b7b tags:
``` python ``` python
n = 7 n = 7
while n >= 5: while n >= 5:
print(n) print(n)
n -= 1 n -= 1
# Answer is 4. # Answer is 4.
# Loop condition line always gets executed number of # Loop condition line always gets executed number of
# iterations + 1 times. # iterations + 1 times.
``` ```
%% Cell type:markdown id:4def9307 tags: %% Cell type:markdown id:7cf19523 tags:
Refactor the below function. Refactor the below function.
%% Cell type:code id:9421ad49 tags: %% Cell type:code id:a313a32f tags:
``` python ``` python
def is_between(a, b, c): def is_between(a, b, c):
"""Return True if b is between a and c (exclusive), """Return True if b is between a and c (exclusive),
False otherwise""" False otherwise"""
if a < c: if a < c:
if a < b and b < c: if a < b and b < c:
return True return True
else: else:
return False return False
elif c <= a: elif c <= a:
if c < b and b < a: if c < b and b < a:
return True return True
else: else:
return False return False
else: else:
return False return False
print(is_between(1, 3, 2)) # False print(is_between(1, 3, 2)) # False
print(is_between(5, 11, 20)) # True print(is_between(5, 11, 20)) # True
print(is_between(20, 3, 5)) # False print(is_between(20, 3, 5)) # False
print(is_between(50, 11, 9)) # True print(is_between(50, 11, 9)) # True
print(is_between(4, 4, 4)) # False print(is_between(4, 4, 4)) # False
``` ```
%% Output %% Cell type:code id:7fd82ae9 tags:
False
True
False
True
False
%% Cell type:code id:21951d05 tags:
``` python ``` python
def is_between_v2(a, b, c): 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(1, 3, 2)) # False
print(is_between_v2(5, 11, 20)) # True print(is_between_v2(5, 11, 20)) # True
print(is_between_v2(20, 3, 5)) # False print(is_between_v2(20, 3, 5)) # False
print(is_between_v2(50, 11, 9)) # True print(is_between_v2(50, 11, 9)) # True
print(is_between_v2(4, 4, 4)) # False print(is_between_v2(4, 4, 4)) # False
``` ```
%% Output %% Cell type:markdown id:ca9037f7 tags:
False
True
False
True
False
%% Cell type:markdown id:0f71dc12 tags:
Trace the output without using Python interpreter Trace the output without using Python interpreter
%% Cell type:code id:b942d01f tags: %% Cell type:code id:ec8b1b32 tags:
``` python ``` python
x = 1 x = 1
while x < 5: while x < 5:
y = 1 y = 1
while y < 10: while y < 10:
print (x * y, "\t", end="") print (x * y, "\t", end="")
y += 1 y += 1
print() print()
x += 1 x += 1
``` ```
%% Cell type:code id:7743e03b tags: %% Cell type:code id:74060bc4 tags:
``` python ``` python
width = 9 width = 9
height = 4 height = 4
symbol = '#' symbol = '#'
row = 0 row = 0
while row < height: while row < height:
col = 0 col = 0
if row % 2 == 1: if row % 2 == 1:
print(" ", end="") print(" ", end="")
while col < width: while col < width:
print(symbol + ' ', end="") print(symbol + ' ', end="")
col += 1 col += 1
# displays just a newline # displays just a newline
print() # recall default value for end parameter is "\n" print() # recall default value for end parameter is "\n"
row += 1 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