Lesson 9 of 30
In progress
While loops, break and continue
Repeat until something changes, escape an endless loop, and use break and continue without making code hard to follow.
Some jobs do not have a known size. "Keep asking until the answer is valid" cannot be written with a for loop over a fixed range. A while loop repeats for as long as a condition holds.
What you will learn
- Write a
whileloop with a condition that can actually become false. - Use
breakto leave early andcontinueto skip one pass. - Recognise and escape an endless loop.
Repeat while something is true
A while loop checks its condition before every pass. If the condition is true, it runs the body and checks again. The body must change something that affects the condition, or the loop never ends.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
while countdown > 0:
print(countdown)
countdown -= 1
print("Lift off")
Press Run to see the output.
Trace it once with a pencil: 3 is greater than 0, print 3, subtract to 2. Repeat, then 1, then 0 fails the check and the loop ends. That trace is how you debug a loop that behaves strangely.
Reading input until it is valid
This is the natural home of while. You cannot know how many attempts a person needs, so you keep asking until the value makes sense.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
while age < 0:
age = int(input("Age: "))
print("Recorded:", age)
Press Run to see the output.
The starting value of -1 is what gets the loop in the door. If you started at 0, the loop would be skipped entirely, and you would never ask. This is a common bug with sentinel values.
break and continue
break leaves the nearest loop immediately. continue skips the rest of this pass and jumps back to the condition. Both affect only the innermost loop.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print("—")
for number in range(1, 6):
if number % 2 == 0:
continue
print(number)
Press Run to see the output.
The first loop prints 1 to 4 and stops. The second prints 1, 3 and 5. Neither is wrong, but a loop with several break statements scattered through it is hard to reason about. Prefer one clear exit. If a loop needs both break and several continue statements, it is usually two loops pretending to be one; move the body into a function and return early instead. A condition should also read as a rule, not a puzzle: while attempts < limit and not won: says what it means.
A menu loop you will write many times
The other natural use of while is a menu: show options, read a choice, act on it, and repeat until the choice is quit. A boolean flag keeps the exit in one place instead of scattering break statements through the body.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
while running:
choice = input("1 add, 2 list, q quit: ").strip().lower()
if choice == "q":
running = False
elif choice == "1":
print("Add chosen")
elif choice == "2":
print("List chosen")
else:
print("Unknown option")
print("Goodbye")
Press Run to see the output.
The flag makes the loop’s lifetime obvious from the first line. break is still fine for an early exit inside a search, but a menu reads better with a flag.
Endless loops are a real hazard
count = 0
while count < 5:
print("still going")
That loop never ends because count never changes. Running it in a terminal fills the screen until you press Ctrl+C. In this site’s runner, a JavaScript endless loop is stopped after five seconds; Python has no such interrupt, which is exactly why you should trace the loop before running it.
A safer pattern is to make the state change the first thing in the body, or to add a guard counter:
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
while attempts < 3:
attempts += 1
print("Attempt", attempts)
Press Run to see the output.
while True: with no break is not "just a loop". It is a program that never gives the user control back. If you write it, put the exit condition immediately inside, and make sure every path through the body can reach it.
Write a loop that asks for a number and keeps asking while the number is negative. Count how many attempts were rejected and print the count with the accepted number.
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
while number < 0:
number = int(input("Positive number: "))
if number < 0:
rejected += 1
print("Accepted:", number)
print("Rejected attempts:", rejected)
Press Run to see the output.
The first value is negative so the loop starts. Each negative answer is counted, and the loop ends as soon as a non-negative number arrives.
Recap
whilerepeats while its condition is true, so the body must change something.breakexits the loop;continueskips one pass.- Start with a value that enters the loop, and trace it before running.
Next, you will combine decisions and loops in a small guessing game that uses everything from this module.
When should I use while instead of for?
How do I stop a runaway loop in a terminal?
”Does
Progress is saved in this browser only. No account, no email.