▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
while loops
Repeat until something changes, and avoid infinite loops.
🎬 Video version coming soon — read it now
A for loop is great when you know how many times to repeat. A while loop repeats as long as a condition stays True, which is perfect when you don't know in advance.
Each time round, Python checks the condition. When count reaches 6, the condition is False and the loop ends.
Example: keep asking until the answer is valid
You can't know how many tries a user will need, so while is the natural choice.
Example: savings goal
The infinite loop
If the condition never becomes False, the loop runs forever:
In Colab, press the stop button next to the cell (or Runtime → Interrupt execution). Then check that something inside the loop moves it towards the end.
for or while?
- Know the number of repeats, or looping over items? Use for.
- Repeat until something happens? Use while.
In one line
while repeats as long as its condition is True, so make sure something inside the loop eventually makes it False.
Share with a friend