"- **McBurney students** should check with their access consultant to make sure they are on the list for CS220. Right now we only have about 40 on the list. If you receive an email with a \"Regular Exam\" location but are expecting a McBurney location, please reach out to me to correct the problem.\n",
"- [Link to Old Exams](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-lecture-material/-/tree/main/Common/old_exams)\n",
"- **Computer Science Learning Center** -- Want extra help? They have [drop-in tutoring](https://docs.google.com/document/d/1w4J7vxqzYCwlzEGSXFT5rA64qjJ8f2Q0OXXX_NOgzUg/edit?tab=t.0) and [1-on-1 tutoring](https://forms.gle/a44SwuRJdBDaAMzW6). Check out the website [here](https://www.cs.wisc.edu/computer-sciences-learning-center-cslc/)."
]
},
{
"cell_type": "markdown",
"metadata": {},
...
...
%% Cell type:markdown id: tags:
## Announcements
-**McBurney students** should check with their access consultant to make sure they are on the list for CS220. Right now we only have about 40 on the list. If you receive an email with a "Regular Exam" location but are expecting a McBurney location, please reach out to me to correct the problem.
-[Link to Old Exams](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-lecture-material/-/tree/main/Common/old_exams)
-**Computer Science Learning Center** -- Want extra help? They have [drop-in tutoring](https://docs.google.com/document/d/1w4J7vxqzYCwlzEGSXFT5rA64qjJ8f2Q0OXXX_NOgzUg/edit?tab=t.0) and [1-on-1 tutoring](https://forms.gle/a44SwuRJdBDaAMzW6). Check out the website [here](https://www.cs.wisc.edu/computer-sciences-learning-center-cslc/).
%% Cell type:markdown id: tags:
## Warmup
%% Cell type:code id: tags:
``` python
# Warmup 1: Based on the code, answer the following questions...
n=7
whilen>=5:
print(n)
n-=1
# How many times is the loop condition evalauated?
# How many times is the loop body executed?
```
%% Cell type:code id: tags:
``` python
# Warmup 2: Write a function to print out a box of #'s of width by height
# e.g.
# print_box(8, 4) prints
# ########
# # #
# # #
# ########
# What are those? v v
defprint_box(width=4,height=4):
pass
print_box(8,4)
```
%% Cell type:code id: tags:
``` python
# Warmup 3: Write a program that takes in exam scores.
# When the user types in -1, print the average of those scores.
total=0# sum
count=0# total number of items
curr_num=0# last number entered
while???:
curr_num=input("Enter a score [0-100]: ")
# TODO: Add the score to the running total and increase count
# TODO: Tell the user the average score
```
%% Cell type:markdown id: tags:
## Reminder
The structure of a `while` loop is:
```
while CONDITION:
#body of loop
#lines of code after loop
```
Recall that the CONDITION should evaluate to True or False. If True then the body of the loop will be executed and control will go back to the CONDITION and repeat. if False then the body is skipped and the lines of code after loop are executed.
%% Cell type:markdown id: tags:
# Iteration 2
## Readings
*[Python for Everybody, 6.4](https://runestone.academy/ns/books/published/py4e-int/iterations/toctree.html)
- 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
- Determine how many times a line of code executes
- inside the body of the loop
- if the code is the condition of a while loop
%% Cell type:markdown id: tags:
## Nested Loops
Like we saw with `if` statements how the body of the `if` statement can contain multiple lines of code, including additional `if` statements, the same is true for `while` loops. There are some common patterns where having one loop inside of another is a good way to solve the problem.
For example, printing out multiple lines of output is commonly done using nested loops. The outer loop is used to advance through the multiple lines of output and the inner loop is used to build up the output for a single line. Take a look at the example below printing out a multiplication table.
Note that the outer loop's control variable, `x`, is which row that is being worked on and printed and the inner loop's control variable, `y`, is which column within that row that is currently being worked on and printed. A few more things to notice -- after every time the inner loop finishes an empty `print()` is executed to advance to the next line and then the trace returns back to the top of the outer loop where the `y` variable is set back to 1 as the next line is started.
Try changing the numbers in the conditions of the two `while` loops and observe how it changes the output.
%% Cell type:code id: tags:
``` python
# Example 1: Nested Loops....one loop inside another loop
# print out a multiplication table
x=1
whilex<5:
y=1
whiley<10:
print (x*y,"\t",end="")
y+=1
print()# adds a newline
x+=1
```
%% Cell type:markdown id: tags:
### You Try It
Complete the code in the cell below by providing the CONDITIONS of the nested loops. The code should print out a checkerboard pattern using hashtags:
```
# # # # # # # #
# # # # # # # #
# # # # # # # #
```
Like with the multiplication table above, you can control how many lines and the length of each line. Here it should be done by modifying the values in the variables `width` and `height`. The variable `row` is the control variable for the outer loop and `col` is the control variable for the inner loop.
%% Cell type:code id: tags:
``` python
width=9
height=3
symbol='#'
row=0
whileCONDITION:
col=0
ifrow%2==1:
print("",end="")
whileCONDITION2:
print(symbol+'',end="")
col+=1
print()# adds a newline
row+=1
```
%% Cell type:markdown id: tags:
## The `break` statement
The `break` statement in a while loop jumps control to the line after the loop.
%% Cell type:markdown id: tags:

%% Cell type:markdown id: tags:
One way to use the `break` statement is as the way to get out of an infinite loop. Take a look at the example below which finds the next prime number from a user entered starting point.
%% Cell type:code id: tags:
``` python
defis_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
ifx<=1:
returnFalse
# 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
whiledivisor<=x-1:
ifx%divisor==0:
returnFalse
divisor+=1
returnTrue
# find the next prime number after a user-entered starting point
start=int(input("Enter a starting value for looking for primes:"))
number=start+1
whileTrue:# NOTE THE USE OF AN INFINITE LOOP
ifis_prime(number):
print ("the next prime after",start,"is",number)
break# HERE IS HOW YOU GET OUT OF THE LOOP
else:
number+=1
```
%% Cell type:markdown id: tags:
### You Try It
The example below is the one letting users enter scores and then printing out the average. Here we tell the user to enter the string "q" to quit. Can you finish the code so the loop will exit when the user types a "q" and then calculate and print the average of the entered scores.
%% Cell type:code id: tags:
``` python
# Taking our warmup example, now let the user quit by typing in q
total=0# sum
count=0
whileTrue:
score=input("Enter a score [0-100] or q to quit: ")
# TODO: If the user types q, quit.
total+=float(score)
count+=1
print('The average score is',(total/count))
# TODO: At the end, tell the user the average score as well as how many scores were entered.
```
%% Cell type:markdown id: tags:
## The `continue` statement
A `continue` statement in a while loop jumps back to the while condition.
%% Cell type:markdown id: tags:

%% Cell type:markdown id: tags:
Like the `break` statement the flow of execution is changed but instead of going outside of the loop, control goes back to the top of the loop. This is useful when you need to start again. For example, in our getting scores, if a user types in an invalid value, you can print a message and then go back to the top of the loop so they start again. Take a look at the code below.
%% Cell type:code id: tags:
``` python
# Taking our break example, now check if the user input a valid score [0-100].
# If they did not, re-prompt them to enter a score.
total=0# sum
count=0
whileTrue:
score=input("Enter a score [0-100] or q to quit: ")
ifscore=='q':
break
score=float(score)
ifscore<0orscore>100:
print("Invalid input")
continue
total+=float(score)
count+=1
print('The average score is',(total/count))
print('Quitting!')
print('The overall average was ',(total/count))# BONUS: What could go wrong here?
print(count,'scores were collected')
```
%% Cell type:markdown id: tags:
## Using `break` and `continue` within nested loops
When you use `break` and `continue` within nested loops they affect the **inner most loop**. Look at the silly example below.
First, try playing the code with the way it is written now. It works (mostly), but see if you can cheat. Then you can go through the code and make improvements.
%% Cell type:code id: tags:
``` python
# Acey Deucey Game
# The game works, but has some flaws. Let's improve it using what we just learned!
# Complete the TODOs in numbered order, beginning with TODO #0 and ending with TODO #4 (5 total).
# If you get stuck, go to the next cell for a list of hints.
# TODO #0: Play the game! :) Can you cheat?
importrandom
chips=10
num_rounds=5
current_round=1
print("Welcome to Acey Deucey!")
print("You have",chips,"chips.")
# TODO #1: Are we actually going to play 5 rounds? Fix this.
whilecurrent_round<num_rounds:
# Draws 2 random cards
card1=random.randint(1,13)
card2=random.randint(1,13)
print("Your Cards:",card1,"\t",card2)
# TODO #2: If the dealt cards are the same, re-deal.
wager=int(input("How much do you want to wager? "))
# TODO #4: If the user enters a bad wager or does not have enough chips, re-prompt them.
mid_card=random.randint(1,13)
print("The middle card was",mid_card)
ifwager!=0:
ifcard1<mid_card<card2orcard2<mid_card<card1:
print('You win',wager,'chips!')
chips+=wager
else:
print('You lose',wager,'chips!')
chips-=wager
else:
print('You did not wager anything, therefore you did not win or lose!')
# TODO #3: If you are out of chips, leave the table.
print("You have",chips,"chips.")
current_round+=1
print("Thanks for playing!")
print("You left with",chips,"chips.")
```
%% Output
Welcome to Acey Deucey!
You have 10 chips.
Your Cards: 3 10
How much do you want to wager? 10
The middle card was 12
You lose 10 chips!
You have 0 chips.
Your Cards: 6 9
How much do you want to wager? -20
The middle card was 7
You win -20 chips!
You have -20 chips.
Your Cards: 4 12
How much do you want to wager? -40
The middle card was 13
You lose -40 chips!
You have 20 chips.
Your Cards: 10 9
How much do you want to wager? -20
The middle card was 9
You lose -20 chips!
You have 40 chips.
Thanks for playing!
You left with 40 chips.
%% Cell type:markdown id: tags:
### HINTS On Fixes:
Use these suggestions for making fixes and improvements to the code:
* For TODO 0, try betting with negative or an outlandish number of chips.
* For TODO 1, we currently have an off-by-1 error
* For TODO 2, we should use a continue statement
* For TODO 3, we should use a break statement
* For TODO 4, we should use a nested while loop
%% Cell type:markdown id: tags:
## Summary
You have learned about nested loops and the use of the `break` and `continue` statements within loops, including the fact that when these statements are used the change the flow of control within the inner most loop.