Editor

Fix the Bug: Sum Until Negative

Beginner · Fix the bug · from Python break, continue, pass: Controlling Loop Flow

From the lesson: Python break, continue, pass: Controlling Loop Flow

You're searching through a phone book for your friend's number. Once you find it, do you keep flipping through every remaining page? Of course not - you stop. Or imagine you're reading a list of emails. You skip the spam and only read the real ones. These are everyday examples of controlling the flow of a loop.

Read the lesson

This code should add up numbers from the list until it hits a negative number, then stop. But someone used continue instead of break. Fix the bug so it prints:

Sum before negative: 15

Don't change anything except the one wrong keyword.

numbers = [5, 3, 7, -2, 8, 4]
total = 0
for num in numbers:
if num < 0:
continue # BUG: this should stop, not skip!
total += num
print(f"Sum before negative: {total}")

More break, continue, pass exercises

All Python exercises · 50 practice problems · Control Flow quiz