We return to the topic of iteration! A while
loop allows us to deal with indefinite iteration--iterating an unknown (or not easily knowable) number of times until some stopping condition is reached.
while
statement
break
break
in any work you submit in CS1110. We want you to know about this keyword, but you should not use it (for now). Instead, practice using the while
loop in situations where the while
loop is well suited.
for
loop and the while
loop for calculating the sums of squares (total.py, flow.py)range
with a while
loop (pattern1.py)while
loops: use a goal condition; use a boolean tracking variable (pattern2.py, pattern3.py)Slides: individual slides for viewing, 6-up layout for printing
Examples: guessNumber.py, guessNumberSkeleton.py, guessNumberLimitGuesses.py, euclid.py
Optional extra practice (last slide): Modify the game
module from last lecture for guessing a secret word to use a while
loop instead of recursion. Play the game to check your code! Then take a look at our solution here. Which solution do you prefer, recursion or while
loop?
Optional reading: On loop invariants