Python for loops and while loops
for loop, while loop, range function, break, continue, else on loops, infinite loop prevention
Loops
Python has two loop types. Use for when the number of iterations is known; use while when looping until a condition changes.
For Loop
for i in range(5): # 0 1 2 3 4
print(i)
for i in range(2, 10, 2): # 2 4 6 8
print(i)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
While Loop
count = 0
while count < 5:
print(count)
count += 1 # always modify the condition variable
Break and Continue
for n in range(10):
if n == 3:
continue # skip 3
if n == 7:
break # stop at 7
print(n) # 0 1 2 4 5 6
A for/while loop can have an else block that runs only when the loop finishes without hitting break. Guard every while loop with a clear exit condition or a counter โ missing this causes infinite loops.
A common mistake with while loops is forgetting to update the loop variable, causing an infinite loop. If you accidentally start one in the terminal, press Ctrl+C to interrupt. The range() function does not create a list โ it returns a lazy range object that generates values on demand, making it memory-efficient even for large counts. When iterating over a sequence and also needing the index, use enumerate(iterable) instead of manually tracking a counter. This is more idiomatic and less error-prone.
