Loops are how programs do the boring work a million times without complaining. Python's for loop is famously clean — once you stop fighting range() and off-by-ones.
for item in sequence: visits each element. range(5) gives 0-4. while condition: repeats until false. break exits the loop, continue skips to the next round. Need the index too? for i, item in enumerate(items):.
for letter in "abc":
print(letter) # a b c
scores = [90, 85, 77]
for s in scores:
print(s * 2)
for i in range(5): # 0 1 2 3 4 — five numbers, ends BEFORE 5
print(i)
for i in range(2, 11, 2): # start, stop, step → 2 4 6 8 10
print(i)count = 3
while count > 0:
print(count)
count -= 1 # forget this line = infinite loop!
print("liftoff 🚀")
# the input-validation pattern:
answer = ""
while answer not in ("yes", "no"):
answer = input("yes or no? ").lower()for n in range(1, 100):
if n * n > 50:
print(f"first square over 50: {n*n}")
break # exit loop entirely
for n in range(10):
if n % 2 == 0:
continue # skip evens, go to next n
print(n) # 1 3 5 7 9names = ["ada", "alan", "grace"]
for i, name in enumerate(names, start=1):
print(f"{i}. {name}") # numbered list, no manual counter
scores = [95, 88, 92]
for name, score in zip(names, scores):
print(f"{name}: {score}") # two lists in parallelfor row in range(3):
for col in range(3):
print(f"({row},{col})", end=" ")
print() # newline after each row
# total iterations = 3 × 3 = 9 — nesting multiplies work!for x in items: skips elements — loop over items[:] (a copy) insteadUse for when you know what you're looping over (a list, a range, a file); use while when you loop until some condition changes, like waiting for valid input.
Start at 1, stop before 10, step by 2 — producing 1, 3, 5, 7, 9.
Wrap the sequence with enumerate(): for i, item in enumerate(items). Avoid the manual counter pattern.
A while loop whose condition never becomes False. Press Ctrl+C to interrupt it, then make sure something inside the loop updates the condition.