6 of 6
The most common loop bug! Remember: range(5) gives 0, 1, 2, 3, 4 — it stops before 5.
# ❌ Prints 0 to 4 (not 1 to 5) for i in range(5): print(i) # ✅ Prints 1 to 5 for i in range(1, 6): print(i)
If you forget to update the condition variable, the loop runs forever:
# ❌ Infinite loop — count never changes! count = 0 while count < 5: print(count) # ✅ Fixed — count increases each time count = 0 while count < 5: print(count) count += 1
If your program freezes, you probably have an infinite loop. Press Ctrl+C to stop it.
Don't add or remove items from a list while looping over it — this causes unexpected behavior:
# ❌ Dangerous — skips items! items = [1, 2, 3, 4, 5] for item in items: if item % 2 == 0: items.remove(item) # ✅ Safe — loop over a copy items = [1, 2, 3, 4, 5] for item in items[:]: if item % 2 == 0: items.remove(item)
for vs whilefor when you know how many times to loop (or looping over a list)while when you're waiting for something to happen# for — known count for i in range(10): print(i) # while — unknown count (depends on user) password = "" while password != "secret": password = input("Password: ")
Start with an initial value and build it up inside the loop:
# Sum of numbers total = 0 for n in [10, 20, 30]: total += n print(total) # 60 # Building a string message = "" for word in ["Hello", "World"]: message += word + " " print(message) # "Hello World " # Collecting into a list evens = [] for i in range(10): if i % 2 == 0: evens.append(i) print(evens) # [0, 2, 4, 6, 8]
When your loop isn't working right:
range(3) instead of range(100) while debugging