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.

Activities before lecture

First read 2 short sections from Ch 7 of textbook

  1.   7.3 The while statement
  2.   7.4 break
    Do not use 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.

Next watch lesson videos

  1. While-Loop Traces (9 minutes) Compare the for loop and the while loop for calculating the sums of squares (total.py, flow.py)
  2. While-Loop Ranges (6 minutes) Warm up by replacing a for-loop that iterates over a range with a while loop (pattern1.py)
  3. While-Loop Patterns (6 minutes) Two typical patterns for setting up while loops: use a goal condition; use a boolean tracking variable (pattern2.py, pattern3.py)

Lecture materials

Slides: individual slides for viewing, 6-up layout for printing

Examples: guessNumber.py, guessNumberSkeleton.py, guessNumberLimitGuesses.py, euclid.py

Lecture Recording

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