Python Loops
Iterate with for and while loops, break, continue, and enumerate
Overview
Loops repeat code over sequences or while a condition holds. Python favors for loops over index-based iteration—use range(), enumerate(), and zip() instead of manual counter variables when possible.
Syntax / Usage
# for loop over a sequence
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# range(start, stop, step)
for i in range(3):
print(i) # 0, 1, 2
# while loop
count = 0
while count < 3:
count += 1
# break and continue
for n in range(10):
if n == 5:
break # exit loop
if n % 2 == 0:
continue # skip to next iteration
print(n)
# enumerate for index + value
for index, value in enumerate(["a", "b"]):
print(index, value)
Examples
Sum numbers until the user types quit:
total = 0
while True:
line = input("Enter a number (or 'quit'): ")
if line == "quit":
break
total += int(line)
print(f"Total: {total}")
Find the first even number in a list:
numbers = [1, 3, 5, 8, 9]
for n in numbers:
if n % 2 == 0:
print(f"First even: {n}")
break
else:
print("No even numbers found")
Common Mistakes
- Modifying a list while iterating over it—iterate over a copy instead
- Infinite
while Trueloops without abreakcondition - Using
range(len(items))whenenumerate(items)is clearer - Off-by-one errors with
rangestop values (stop is exclusive)
See Also
python-list-comprehension python-functions python-dictionaries