Python loop exercises
Most beginner bugs live inside a loop: it runs one time too many or too few, it never stops, or it returns after the first pass. These exercises are short loops with exactly one of those mistakes.
Trace the loop by hand for a small input, find where it goes wrong, and fix it. Infinite loops are stopped safely after a few seconds, so you cannot hang your browser.
The loops bugs you will meet
- range(1, n) stops at n - 1; range(1, n + 1) includes n.
- A return inside the loop ends the function on the first pass.
- A while loop whose variable never changes, or steps over its stop value, never ends.
- Setting the total inside the loop resets it on every pass.
- Changing a list or dict while looping over it skips items or crashes.
The exercises
Easy
- Sum from 1 to n leaves out nOff-by-one
- Last even number crashes when there is noneScope and closure
- Retry loop never stops on successInfinite loops
- Countdown never reaches zeroOff-by-one
- Vowel counter skips capital lettersLogic
- Shopping total crashes at the end of the listOff-by-one
- Letter counter crashes on the first letterNull and undefined
Medium
- Countdown never stopsInfinite loops
- Adding up digits never finishesInfinite loops
- Adding to total crashes with UnboundLocalErrorScope and closure
- Removing double spaces freezesInfinite loops
- Collatz steps freeze on odd numbersInfinite loops
- Biggest gap between numbers comes out as -1Logic
- AI Attempt: The Two Sum TrapLogic
- Highest temperature reads 0 on a cold dayLogic
Errors you might be searching for
More Python practice by topic
Questions
What happens if my fix creates an infinite loop?
The test is stopped after a few seconds and marked as timed out. Your browser stays responsive.
Can I see the loop run step by step?
Yes. After a run, the line-by-line view shows every variable at every step, which is the fastest way to see where a loop goes wrong.