Home βΊ Problems βΊ break vs continue
break vs continue
π§ Predict the output Topic: loops Difficulty: medium Free
What this problem practises
Loops are where off-by-one bugs live. range() excludes its stop value, the loop variable keeps its last value even after the loop ends, and break versus continue changes the flow in ways that are easy to misread when you skim.
This is an output-prediction problem: read the snippet carefully and write down exactly what it prints before anything runs. These questions are interview staples because they test whether you know the language rules, or merely recognise their syntax.
Difficulty: medium β expect to hold two interacting rules in your head at once, such as a boundary combined with a mutation.
The challenge
The code runs in PyDebugβs in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.
The snippet
The interactive editor pre-fills exactly this code β read it, then submit your prediction:
for i in range(1, 6):
if i == 3:
continue
if i == 5:
break
print(i)Understand the rule
break and continue are the two ways a loop body can interrupt itself, and they do opposite things: break abandons the whole loop immediately, continue abandons only the current pass and jumps to the next iteration. Predicting this snippet means tracking exactly which iterations execute the statements after the keyword β and which never reach them.
How to trace it
- Walk the loop iteration by iteration, writing the loop variable's value each pass.
- When continue fires, skip the rest of the body but keep looping: the next value still arrives.
- When break fires, stop the loop entirely: no further values, and execution resumes after the loop.
- Remember break also skips a for-loop's else block, while a loop that merely continues to completion still runs it.
Common wrong fixes
- Reading continue as 'continue running this body' when it means 'continue with the NEXT iteration'.
- Forgetting that statements between the keyword and the end of the body are skipped on that pass.
- Assuming break exits nested loops; it only exits the innermost one containing it.
Rule to remember
continue skips the rest of one pass; break kills the loop. Trace which values reach the code below the keyword, and the printed output falls out mechanically.
π Learning path: Loops
Problem 10 of 16 in this path. Work them in order β each one builds on the rule before it.
More loops problems
Keep going
- Output-prediction strategies β how to predict tricky snippets without running them.
- Browse every loops problem in this topic.
- Common Python errors and what they actually mean, plus the Python glossary for any term used on this page.