← Back

Home β€Ί Problems β€Ί Loop variable after the loop ends

Loop variable after the loop ends

🧠 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(5):
    pass
print(i)
print(i * 2)

Understand the rule

In Python, a for loop's variable is not scoped to the loop β€” after the loop finishes, the variable still exists and holds the last value it was assigned. print(i) after 'for i in range(3)' prints 2, not an error. This snippet tests that rule plus its corollaries: with break, the variable keeps the value at the moment of breaking; on an empty iterable, it was never assigned at all.

How to trace it

  1. Run the loop mentally to completion and note the final value the variable received.
  2. If a break fired, freeze the variable at the value that triggered the break instead.
  3. If the iterable was empty, the variable was never created β€” a later read raises NameError.
  4. Read the post-loop statements with that surviving value.

Common wrong fixes

Rule to remember

Loop variables outlive their loop and hold the last assigned value β€” range(n) leaves n-1 behind. Only an empty iterable leaves the name undefined.

Solve it in the interactive editor β†’

πŸ” Learning path: Loops

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

← enumerate with a start valueNext in path: else clause on a for loop β†’

πŸ’Ό Learning path: Interview Practice

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

← List multiplicationNext in path: else clause on a for loop β†’

More loops problems

Keep going