Home βΊ Problems βΊ for loop with range and step
for loop with range and step
π§ 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(10, 0, -2):
print(i, end=" ")Understand the rule
range(start, stop, step) counts from start toward stop in jumps of step, always excluding stop itself. The step makes the last value non-obvious: range(0, 10, 3) ends at 9, range(1, 10, 3) at 7. Negative steps count down and need start greater than stop, or the range is silently empty. Predicting these loops is about computing the actual final value, not assuming stop minus one.
How to trace it
- Generate values mechanically: start, start+step, start+2*step, ... while still on the near side of stop.
- Stop before crossing stop β the last value is the largest (or smallest, for negative step) that hasn't reached it.
- For negative steps check the direction: range(1, 10, -1) can never move from 1 toward 10, so it yields nothing.
- Count the values if the question asks for iteration count: it is ceil((stop - start) / step) for a non-empty range.
Common wrong fixes
- Assuming the sequence always ends at stop - 1; with step > 1 the true last value depends on alignment.
- Writing range(10, 0) for a countdown and getting an empty range because the default step is +1.
- Off-by-one on the countdown bound: range(10, 0, -1) ends at 1, never 0.
Rule to remember
With a step, generate the sequence value by value until the next jump would reach or pass stop. The stop is excluded in every direction, and a range that cannot move toward its stop is empty.
π Learning path: Loops
Problem 12 of 16 in this path. Work them in order β each one builds on the rule before it.
β Previous problemNext in path: enumerate with a start value β
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.