Back

Debug Challenge: Loops

Difficulty  

divider

Objective

Four broken loops. None of them crash. One of them never stops.

These are the four loop bugs you are most likely to write yourself during Group Project 1, so it is worth being able to recognize all four on sight.

Skills to Practice

  • Recognizing why a loop never ends
  • Checking what range() actually produces
  • Knowing what belongs inside the loop and what belongs before it
  • Reading indentation as meaning

Before You Run Bug 1

Bug 1 is an infinite loop. It will print forever and will not stop on its own.

Press Ctrl + C in the terminal to kill it. Get used to that now — every programmer writes an infinite loop eventually, and knowing how to stop one is part of the job.


The Four Programs

For each one: what is wrong, and what is the corrected line? All four are logic errors, so no traceback is coming to help you.


Bug 1

Symptom: prints You lost a life! forever. Game over. never prints.

Bug 1
lives = 3
while lives > 0:
print("You lost a life!")
print("Game over.")

The condition on line 3 is correct. Ask yourself what would ever have to change for it to become false, and whether anything in the loop changes it.


Bug 2

Symptom: counts 1 through 9. The 10 never appears.

Bug 2
print("Counting to 10:")
for number in range(1, 10):
print(number)

An off-by-one. Write down exactly which numbers range(1, 10) produces, then fix it.


Bug 3

Symptom: prints Total: 15. The three scores add up to 27.

Bug 3
print("Adding up your scores.")
for score in [4, 8, 15]:
total = 0
total = total + score
print("Total:", total)

Notice that 15 is the last score in the list. That is the clue. One line is in the wrong place — which line, and where should it go instead?

This is the single most common loop bug there is. Once you have seen it, you will recognize it for the rest of your life.


Bug 4

Symptom: prints all three rounds, then You scored a point! exactly once at the end, instead of once per round.

Bug 4
for round_num in range(1, 4):
print("Round", round_num)
print(" You scored a point!")

The extra spaces at the start of that message make it look like it belongs to the loop. Looking indented and being indented are not the same thing.


Submit

  • One sentence on what was wrong with each
  • The corrected line, and where it belongs

Then this: Bugs 3 and 4 are both about a line being in the wrong place. What is the difference between them?

Commence Debugging