Beginner·5 min·basics · loops
While Loops & break/continue
You’ll be able to
- Write
whileloops that terminate correctly - Use
breakto exit a loop early - Use
continueto skip to the next iteration - Avoid infinite loops with proper counter logic
Why this matters
while powers retry logic, polling loops, and event listeners in real backends. Every requests retry helper, every websocket reader, every game loop is a while True with a smart break condition.
Common pitfalls
- Forgetting to update the loop variable:
while i < 10: print(i)runs forever. Always mutate state inside the body. - Using
while Truewithout abreak. Ctrl+C is the only exit, and in production that means a hung worker. - Confusing
continuewithbreak.continueskips to the next iteration;breakexits the loop entirely.
A while loop runs as long as a condition is true. Use it when you don't know up-front how many times you'll loop.
Two escape hatches
break— exit the loop immediatelycontinue— skip to the next iteration
Pitfall
Forgetting to update the condition variable → infinite loop. Always ask "what makes this stop?"
Try it
- Read user input in a loop until they type "quit". (Use a hardcoded list for now.)
- Skip negative numbers in a list with
continue.
Practice
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
Progress0 / 3
- Exercise 1
Use a
whileloop to compute the sum of integers from1to100(inclusive). Print just the total. Expected:5050. - Exercise 2
Find the first power of 2 greater than 1,000. Print just that number.
- Exercise 3
Print numbers
1..15but skip multiples of 3 (usecontinue). One number per line.