Home βΊ Problems βΊ Loop sum from 3 to 5
Loop sum from 3 to 5
π§ Predict the output Topic: loops Difficulty: easy 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: easy β the fix or the trick is normally a single line, and a careful read should be enough.
The challenge
What will this program print? Type the exact output.
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:
total = 0
for i in range(3, 6):
total += i
print(total)Understand the rule
Accumulator loops initialize a running total (usually `total = 0`) before a `for` loop and add each element from `range(...)` on every pass. Predicting the exact total comes down to checking the starting accumulator value and whether the upper `range` bound is `5` or `6`.
How to trace it
- Check the initial value of the accumulator variable right before the loop begins.
- Expand `range(a, b)` into its exact integer list β `range(3, 6)` yields `3, 4, 5`, whereas `range(3, 5)` yields only `3, 4`.
- Add each yielded integer to the accumulator one iteration at a time.
- Check indentation of `print(total)` β outside the loop prints once at the end; indented inside prints after every addition.
Common wrong fixes
- Assuming `range(3, 5)` includes `5` (`3 + 4 + 5 = 12`) when `range` always excludes its stop argument (`3 + 4 = 7`).
- Missing a non-zero starting accumulator (such as `total = 1` or `total = 10`) before the loop.
- Overlooking `print()` indentation and writing one final number when the `print()` actually sits inside the loop body.
Rule to remember
Write out the exact numbers from `range(...)` on one line and check `print` indentation before summing.
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.