Home โ€บ Output practice โ€บ for loop with range

Predict the output: for loop with range()

๐Ÿ”ฎ Predict the outputTopic: loopsDifficulty: mediumNo login needed

The snippet

Two rules interact here: what range(1, 10, 3) actually generates, and what the loop variable holds after the loop ends. The final print is where most predictions break. Write every line, including the last one.

total = 0
for i in range(1, 10, 3):
    total += i
    print(i, total)
print("end", i)

Your prediction

Type exactly what this program prints โ€” one line per print() call:

The output

1 1
4 5
7 12
end 7

Line-by-line explanation

  1. range(1, 10, 3)
    Generates 1, 4, 7 โ€” then the next jump (10) would reach the stop, and the stop is always excluded. Three iterations, last value 7, never 9 or 10.
  2. total += i (pass 1)
    i = 1, total = 0 + 1 = 1 โ†’ prints 1 1.
  3. total += i (pass 2)
    i = 4, total = 1 + 4 = 5 โ†’ prints 4 5.
  4. total += i (pass 3)
    i = 7, total = 5 + 7 = 12 โ†’ prints 7 12.
  5. print("end", i)
    Loop variables survive the loop in Python and keep their last value โ€” i is still 7 โ†’ prints end 7. No NameError (that happens only when the iterable was empty).

Share your result

Challenge a friend โ€” the link contains the question, never the answer:

Copied โœ“

Keep practising this rule

More output questions โ†’ All interactive problems