How do loops (for and while) work in Python?

· Category: Python Programming

Short answer

Python provides for loops for iterating over sequences and while loops for repeating while a condition is true. Use break to exit early, continue to skip to the next iteration, and else to run code when the loop completes without breaking.

Steps

  1. Use for item in iterable: to iterate.
  2. Use while condition: for condition-based repetition.
  3. Control flow with break, continue, and else.
# for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# while loop
count = 0
while count < 3:
    print(count)
    count += 1

# range
for i in range(5):
    print(i)

Tips

  • range(start, stop, step) is the idiomatic way to loop a specific number of times.
  • The else clause on a loop runs only if the loop did not encounter a break.
  • Use enumerate() when you need both the index and the value.
  • Use zip() to iterate over multiple sequences in parallel.
names = ["Alice", "Bob"]
scores = [90, 85]
for idx, name in enumerate(names):
    print(f"{idx}: {name}")

for name, score in zip(names, scores):
    print(f"{name} -> {score}")

Common issues

  • Modifying a list while iterating over it can skip elements or cause errors; iterate over a copy instead.
  • Forgetting to update the loop variable in a while loop causes infinite loops.
  • range() excludes the stop value.