Lesson 5 of 52First steps
Loops
Repeat work with for and while, control it with break and continue, and use range, enumerate and zip like a pro.
Computers are good at doing the same thing a million times without getting bored. Sending an email to every subscriber, summing every order, retrying a request until it works: all loops. Python's loops are simpler than most languages', and learning the idiomatic forms (enumerate, zip) is one of the fastest ways to make your code look like a professional wrote it.
for loops walk through a sequence
A for loop takes each item from a sequence, one at a time, binds it to a name, and runs the indented block.
Press Run (⌘ Enter) to see what happens.total += price is shorthand for total = total + price. The same works for -=, *= and the others.
Before the loop, total starts at 0.
Python's for works on anything iterable: lists, strings, dicts, files, and more. You never manage an index counter by hand unless you actually need one.
range: counting loops
When you want to repeat something a number of times, or need the numbers themselves, use range.
range(5)gives 0, 1, 2, 3, 4. Five numbers, starting at 0, and the stop value is not included.range(2, 6)gives 2, 3, 4, 5.range(10, 0, -3)gives 10, 7, 4, 1. The third value is the step.
Press Run (⌘ Enter) to see what happens.range does not build a list in memory. It produces numbers on demand, so range(1_000_000_000) costs almost nothing until you loop over it. (list(...) above is only there to show the numbers.)
What does this print?
for i in range(1, 10, 3): print(i)
while loops: repeat until something changes
A while loop repeats as long as its condition is true. Use it when you do not know in advance how many times you need: waiting for valid input, halving a number until it reaches 1, retrying a request.
Press Run (⌘ Enter) to see what happens.The danger is an infinite loop: a condition that never becomes false. Each pass must change something the condition depends on. If you forget years += 1 in a counting loop or the update in the line above it, the program hangs. (Press the stop button, or Ctrl+C in a terminal.)
i = 0 while i < 5: print(i)
break, continue, and for...else
Two keywords change the flow inside any loop:
breakleaves the loop immediately.continueskips the rest of this pass and goes on to the next item.
Press Run (⌘ Enter) to see what happens.Python has an unusual extra: a loop can have an else block. It runs only if the loop finished without hitting break. That makes "search, and do something if not found" tidy, with no flag variable:
Press Run (⌘ Enter) to see what happens.What does this print?
for n in [3, 5, 8, 9]:
if n % 2 == 0:
print("even:", n)
break
else:
print("no evens")enumerate and zip
Two built-ins replace most hand-written index counters.
enumerate gives you the index and the item together. zip walks two or more sequences side by side.
Press Run (⌘ Enter) to see what happens.The beginner version, for i in range(len(names)): followed by names[i], works but is noisier and easier to get wrong. Reach for enumerate when you need the position and zip when you need to pair things up.
One zip detail: it stops at the shortest input, silently dropping extras. In Python 3.10+ you can pass strict=True to get an error instead when the lengths differ.
Match each task to the best tool.
Nested loops and what they cost
A loop inside a loop runs the inner block once for every pair of items. That is perfect for grids and tables:
Press Run (⌘ Enter) to see what happens.But it gets expensive fast. If both loops run n times, the inner block runs n × n times. Computer scientists write this as O(n²) ("order n squared"): double the input and the work goes up four times. With 1,000 items that is a million steps; with 100,000 items it is ten billion, which takes minutes in Python.
When you see nested loops over the same data, ask whether a smarter structure (a set or dict, coming soon in the Collections unit) could make it one pass.
FizzBuzz
Write fizzbuzz(n) that returns a list of strings for the numbers 1 to n:
"FizzBuzz"if the number is divisible by both 3 and 5"Fizz"if divisible by 3"Buzz"if divisible by 5- otherwise the number itself as a string
fizzbuzz(5) → ["1", "2", "Fizz", "4", "Buzz"]Collatz steps
Start with a positive whole number n. If it is even, halve it. If it is odd, replace it with 3 * n + 1. Repeat until you reach 1.
Write collatz_steps(n) that returns how many steps that takes.
collatz_steps(1) → 0
collatz_steps(6) → 8 (6, 3, 10, 5, 16, 8, 4, 2, 1)- iterable
- Anything a
forloop can walk through: lists, strings, ranges, dicts, files. - range(start, stop, step)
- Produces numbers on demand from start up to, but not including, stop.
- break / continue
breakexits the loop now;continueskips to the next pass.- for...else
- The
elseblock runs only if the loop finished withoutbreak. - enumerate / zip
enumerategives (index, item) pairs;zipwalks several sequences side by side.- O(n²)
- Work grows with the square of the input size, typical of a loop nested inside another over the same data.