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
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.total += i (pass 1)
i = 1, total = 0 + 1 = 1 โ prints1 1.total += i (pass 2)
i = 4, total = 1 + 4 = 5 โ prints4 5.total += i (pass 3)
i = 7, total = 5 + 7 = 12 โ prints7 12.print("end", i)
Loop variables survive the loop in Python and keep their last value โ i is still 7 โ printsend 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 โ