Loops: for, while & friends
for and while loops, range, enumerate, zip, break/continue, loop else and loop-replacing built-ins.
Computers are great at doing the same thing thousands of times without getting bored. Loops let you process every item in a list, every line in a file, or keep asking until the user gets it right. Python has two loops — for and while — plus some elegant helper functions that make loops read like plain English.
The for loop#
Python's for walks through the items of any iterable — a list, a string, a range, a dictionary, a file — one at a time:
The loop variable (lang, ch) takes each value in turn. There's no index bookkeeping and no risk of going off the end.
Counting with range()#
When you need numbers, use range(stop), range(start, stop) or range(start, stop, step). The stop value is never included:
range doesn't build a list in memory — it produces numbers on demand, so range(1_000_000_000) costs almost nothing. (We wrapped it in list() above just to display it.)
enumerate(): index and value together#
Beginners from other languages often write for i in range(len(items)):. Python has a better way:
zip(): loop over several sequences in parallel#
zip stops at the shortest input. Pass strict=True (Python 3.10+) to raise an error if the lengths differ — a great way to catch bugs.
Looping over dictionaries#
Iterating a dict gives you its keys; use .items() to get key–value pairs:
The while loop#
while repeats as long as a condition is true. Use it when you don't know in advance how many iterations you need:
Make sure something inside the loop eventually makes the condition false, or you'll write an infinite loop (stop a runaway program with Ctrl+C).
A deliberate while True: with a break is a common, readable pattern for "loop until something happens" — for example, a menu or input validation:
break, continue and else#
breakleaves the loop immediately.continueskips the rest of this iteration and moves on to the next.
Loops can have an else clause that runs only if the loop wasn't stopped by break. It's perfect for searches:
Nested loops#
A loop inside a loop runs the inner loop completely for every step of the outer one:
break only exits the innermost loop. To stop everything, move the loops into a function and return.
Handy built-ins that replace loops#
Many loops just compute a summary. Python has built-ins for the common ones:
Worked example: FizzBuzz and a number-guessing game#
The classic interview warm-up:
And a small game that combines while, input and conditionals:
Common mistakes#
- Modifying a list while looping over it. Removing items mid-loop skips elements. Loop over a copy (
for x in items[:]) or build a new list. - Off-by-one with
range.range(1, 10)stops at 9. Userange(1, 11)for 1–10. for i in range(len(items))when you only need the items — loop directly, or useenumerate.- Forgetting to update the
whilecondition, creating an infinite loop.
What's next#
You can now repeat work over collections. Time to study the most important collection of all: the list.
Check your understanding
Quick quiz
1.What does
range(2, 10, 3)produce?2.What does
continuedo inside a loop?3.When does the
elseblock of aforloop run?
Finished reading?
Mark this lesson complete to track your progress.