Loops
for, while, range, break, continue, enumerate
Skills taught: python.for, python.while, python.range, python.enumerate, python.break, python.continue
for loops
# Iterate over a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# apple
# banana
# cherry
# range() — generate a sequence of numbers
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for i in range(2, 8):
print(i) # 2, 3, 4, 5, 6, 7
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8 (step=2)
# Iterate over a string
for char in 'Python':
print(char) # P, y, t, h, o, n
enumerate and zip
# enumerate() — index + value at the same time
names = ['Alice', 'Bob', 'Charlie']
for i, name in enumerate(names):
print(f'{i}: {name}')
# 0: Alice
# 1: Bob
# 2: Charlie
# Start index at 1
for i, name in enumerate(names, start=1):
print(f'{i}. {name}') # 1. Alice, 2. Bob...
# zip() — iterate two lists together
scores = [95, 82, 78]
for name, score in zip(names, scores):
print(f'{name}: {score}')
# Alice: 95 | Bob: 82 | Charlie: 78
while, break, continue
# while loop
count = 0
while count < 5:
print(count)
count += 1
# 0, 1, 2, 3, 4
# break — exit loop early
for i in range(10):
if i == 5:
break
print(i) # 0, 1, 2, 3, 4
# continue — skip current iteration
for i in range(10):
if i % 2 == 0:
continue # skip even numbers
print(i) # 1, 3, 5, 7, 9
# Searching with for-else (unique Python pattern!)
numbers = [3, 7, 2, 9, 4]
target = 99
for n in numbers:
if n == target:
print(f'Found {target}!')
break
else:
print(f'{target} not found') # runs if no break
# → 99 not found
Frequently Asked Questions
How do I loop with both index and value?
Use enumerate(): for i, item in enumerate(my_list): gives you i (0-based index) and item simultaneously. To start at 1: enumerate(my_list, start=1). Avoid the C-style: for i in range(len(my_list)): my_list[i] — it works but is un-Pythonic.
When should I use while vs for?
Use for when you know what you're iterating over (a list, a range, a file). Use while when you're waiting for something to happen (user input, a condition to change, retrying an operation). Prefer for — it's safer (can't accidentally infinite loop on a finite sequence).