csci 1101b while loops - bowdoin collegesharmon/static/1101/lecs/1101_lec11.pdf · why have while...
TRANSCRIPT
While Loops
CSCI 1101B
Today’s Outline
● Iteration (review)
● When Should We Not Use For-Each Loops?
● While Loops
● Controlling Loops○ The Break Statement○ The Continue Statement
Example - First, Recall The Turtle Module
from turtle import *
joe = Turtle()joe.shape("turtle")
Example: Running a Race
joe.forward(100) # The 100 meter dash!done()
# ...but what if we wanted to take # things one step at a time?
# (e.g., perhaps there are # obstacles to look out for!)
Example: Running a Race
joe.forward(1)joe.forward(1)joe.forward(1)joe.forward(1)
# and so on…!
done()
Example: Running a Race
joe.forward(1)joe.forward(1)joe.forward(1)joe.forward(1)
# and so on…!
done()
# How could we make this better?
Example: Running a Race (For-Each Loop)
num_iterations = 4
for i in range(num_iterations): joe.forward(1)
done()
Example: Running a Race (For-Each Loop)
num_iterations = 4
for i in range(num_iterations): joe.forward(1)
done()
# Let’s learn another way...
Example: Running a Race (While Loop)
num_iterations = 4current_num = 0
while current_num < num_iterations: joe.forward(1) current_num += 1
done()
Example: Running a Race (While Loop)
num_iterations = 4current_num = 0 # initialization
while current_num < num_iterations: # test condition joe.forward(1) current_num += 1 # update
done()
Example: Running a Race
Why have while loops if for-each loops work just fine?
Example: Running a Race
Why have while loops if for-each loops work just fine?
What if we didn’t know the number of iterations?
What if we just had a stopping point that would happen at some point along the way?
While Loops
When we don’t know how long a loop will last, we can use a while loop.
while <<condition>>: <<block>>
Example: Running a Race (While Loop)
from random import randint # Lets us get a random int!
simon_says = True
while simon_says: joe.forward(1) if not randint(0, 2): # What’s this mean? simon_says = Falsedone()
Summary: When are For Loops not the best?
What if we don’t know how long a loop should last?
○ “Stir until the mixture is boiling”
○ “Keep the game going until the user quits”
○ “Keep searching for a new answer until you find the right one”
While Loops: Example 2
text = “”
while text != “quit”: text = input(“Enter command or quit: ”)
if text == “quit”: print(“...exiting program.”) elif text == “sing”: print(“La la la, la li da.”) else: print(“Come again?”)
Caution: Infinite Loops
If your test condition never evaluates to False, the instructions will endlessly loop.
while True: print(“This is the song that never ends…”)
Make sure you have a feasible terminating condition to avoid these infinite loops.
(Remember, you can restart the shell if this happens accidentally!) with apologies to Norman Martin
Controlling Loops
Python lets us control iteration in two main ways:
1. We can break out of a loop using the break keyword
2. We can skip ahead to the next iteration with the continue keyword
The Break Statement
text = “”
while True: text = input(“Enter command or quit: ”)
if text == “quit”: print(“...exiting program.”) break if text == “sing”: print(“La la la, la li da.”) print(“Hooray!”)
The Continue Statement
for num in range(10):
if num % 2 == 1:
continue
print(num, end=” ”)
The Continue Statement
for num in range(10):
if num % 2 == 1:
continue
print(num, end=” ”)
This code prints out: 0 2 4 6 8
Good Practice: Don’t use Break/Continue much
What happens when we depend on breaks and continues?
● Loop termination is not clearly explicit
● Encourages lazy programming
● Makes it harder to keep code updated
Summary
When do we use the following?
● For each and while loops
● Break and continue statements
Be careful of infinite loops!