← Back

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

  1. Walk the loop iteration by iteration, writing the loop variable's value each pass.
  2. When continue fires, skip the rest of the body but keep looping: the next value still arrives.
  3. When break fires, stop the loop entirely: no further values, and execution resumes after the loop.
  4. Remember break also skips a for-loop's else block, while a loop that merely continues to completion still runs it.

Common wrong fixes

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.

Solve it in the interactive editor β†’

πŸ” Learning path: Loops

Problem 10 of 16 in this path. Work them in order β€” each one builds on the rule before it.

← Previous problemNext in path: Next problem β†’

More loops problems

Keep going