Loops are how you process collections, files and input one item at a time.
Python's for loop iterates over the items of any iterable — a list, string, dict, file, range — rather than counting an index: for word in words:. To loop a fixed number of times use range: range(5) yields 0..4, range(2, 10, 2) yields 2, 4, 6, 8. The stop value is always excluded.
Resist for i in range(len(items)). Python has better tools:
enumerate(items, start=1)gives(index, item)pairszip(names, scores)walks two iterables in parallel, stopping at the shorter (passstrict=Trueto raise if lengths differ)reversed(items)andsorted(items)loop backwards or in order
A while loop repeats as long as its condition is truthy. Use it when you don't know the number of iterations in advance, such as retrying until input is valid. while True: with a break is a common, clear pattern.
Inside any loop, break exits immediately and continue skips to the next iteration. Loops can also have an else clause, which runs only if the loop finished without hitting break — useful for search loops ("not found").
Don't add or remove items from a list while looping over it; you'll skip elements. Loop over a copy (for x in items[:]) or build a new list instead.
Example
names = ["Ana", "Ben", "Cy"]
scores = [91, 78, 85]
for i, name in enumerate(names, start=1):
print(i, name) # 1 Ana / 2 Ben / 3 Cy
for name, score in zip(names, scores):
print(f"{name}: {score}")
for n in range(10, 0, -3):
print(n, end=" ") # 10 7 4 1
print()
target = 42
for n in [5, 17, 99]:
if n == target:
print("found")
break
else:
print("not found") # not found
count = 0
while count < 3:
count += 1
print(count) # 3Remember
foriterates items directly; useenumerateandzipinstead of indexesrange(start, stop, step)excludesstop- A loop's
elseruns only when nobreakhappened
Watch out for
- Modifying a list while iterating over it.