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
- Use
for item in iterable:to iterate. - Use
while condition:for condition-based repetition. - Control flow with
break,continue, andelse.
# 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
elseclause on a loop runs only if the loop did not encounter abreak. - 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
whileloop causes infinite loops. range()excludes the stop value.