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β Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect
β Functions, classes, recursion, print()
β No file system, subprocess, OS access, or network requests
β No pip install (all supported modules are pre-loaded)
β±οΈ 5 second execution time limit