Module 02 · Lesson 05
Indefinite Loops & Loop Control
Repeat until something changes with while loops, avoid infinite loops, leave a loop early with break, skip an item with continue, and use the loop else clause.
- About 8 minutes
- Beginner friendly
- 12-question quiz at the end
What you will learn
- Loop until done
- Leave early with break
- Skip with continue
- Watch a loop break out
Repeat until something changes
A `while` loop keeps going as long as its condition is `True`. You do not need to know how many rounds in advance.
while
while fuel > 0:checks the question, runs the block, then checks again.Three parts
A start value before the loop, a check at the top and a change inside. Forget the change and it never stops.
break
breakleaves the loop straight away, even if the condition is stillTrue.continue
continueskips the rest of this round and jumps back up to the check.
Loops that wait
Many programs repeat until something happens, not a set number of times.
- Game loopsWhile the player has not quit: read the keys, move everything, draw the screen.
- MicrowavesWhile time is left: wait a second and take one away. At 0, beep.
- DownloadsWhile the file is not finished: fetch the next piece and grow the progress bar.
- AlarmsWhile nobody presses stop: ring again every few minutes.
The first line of a while loop
It looks like an `if`, but it keeps asking. Tap each part to see its job.
Part 1 of 4
keyword:while asks its question at the start of every round, not just once like if.
Loop until done
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6Count down
Start, check, change: the three parts every counting loop needs.
Your turn: Make it count down from 10 in twos.
n = 5
while n > 0:
print(n)
n -= 1
print("Go!")Press Run to see what it prints.Watch a loop break out
Press Step to run one line at a time. Watch the check at the top, and what `break` does.
Ready. Press Step to run the first line.
- coins = 0
- while coins < 20:
- coins += 4
- if coins == 12:
- break
- print("Coins:", coins)
- print("Stopped at", coins)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.Where does it stop?
n = 10
while n > 0:
n -= 3
print(n)0 of 6 answered
Common while loop misconceptions
Each card is something beginners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
while condition: # checked before every iteration
...
update # change something, or it never ends
while True:
if done:
break # leave the loop now
continue # skip to the next iteration
else: # runs only if no break happened
...Press Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Saving up for a bike
Start with 15 in savings and add 12 each week. Work out how many weeks it takes to reach 120, printing the balance each week.
TARGET = 120
savings = 15
weeks = 0
while savings < TARGET:
savings += 12
weeks += 1
print(f"Week {weeks}: {savings}")
print(f"Target reached in {weeks} weeks")Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Forgetting to update the variable
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
n = 1
while n <= 3:
print(n)Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Consumer devices
A phone battery estimate
A phone estimates how many more hours of video it can play, assuming the battery drops 9 percent an hour and the phone switches off below 5 percent.
Why Python fits
The loop does not know the number of hours in advance; it keeps subtracting until another hour would go below the shutdown level. The condition checks the next step before taking it.
Pythonbattery = 64 hours = 0 while battery - 9 >= 5: battery -= 9 hours += 1 print(f"About {hours} hours left, ending at {battery}%")OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Is while True: bad style?
Does break leave every loop?
My program froze. What happened?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 9 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.