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.
range() actually producesBug 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.
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.
Symptom: prints You lost a life! forever. Game over. never prints.
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.
Symptom: counts 1 through 9. The 10 never appears.
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.
Symptom: prints Total: 15. The three scores add up to 27.
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.
Symptom: prints all three rounds, then You scored a point! exactly once at the end, instead of once per round.
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.
Then this: Bugs 3 and 4 are both about a line being in the wrong place. What is the difference between them?