Repeat work with for and while loops, generate number sequences with range, count with enumerate, and control loops using break and continue.
Why: a for loop runs a block of code once for each item in a collection. It is the loop you will reach for most often in Python.
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# apple
# banana
# cherryWhy: range() produces a sequence of numbers, perfect for repeating something a set number of times. range(5) is 0,1,2,3,4 — it stops before the end number.
for i in range(3):
print(i) # 0, 1, 2
for i in range(1, 4):
print(i) # 1, 2, 3 (start, stop)
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8 (start, stop, step)Why: when you need both the position and the item, enumerate() gives you both at once. It is cleaner than tracking a counter variable yourself.
colors = ['red', 'green', 'blue']
for index, color in enumerate(colors):
print(index, color)
# 0 red
# 1 green
# 2 blueWhy: a while loop keeps running as long as a condition stays True. Use it when you do not know in advance how many times to repeat. Make sure something inside eventually makes the condition False, or it runs forever.
count = 3
while count > 0:
print(count)
count = count - 1 # this is what eventually stops the loop
print('Lift off!')Why: break exits the loop immediately. continue skips the rest of the current pass and jumps to the next item. They give you fine control over a loop.
for n in range(10):
if n == 5:
break # stop the loop entirely at 5
if n % 2 == 0:
continue # skip even numbers
print(n) # 1, 3