← Back

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

  1. Generate values mechanically: start, start+step, start+2*step, ... while still on the near side of stop.
  2. Stop before crossing stop β€” the last value is the largest (or smallest, for negative step) that hasn't reached it.
  3. For negative steps check the direction: range(1, 10, -1) can never move from 1 toward 10, so it yields nothing.
  4. Count the values if the question asks for iteration count: it is ceil((stop - start) / step) for a non-empty range.

Common wrong fixes

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.

Solve it in the interactive editor β†’

πŸ” 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