Skip to content

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.

15 min read0/4 questions

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.

Python
prices = [4, 10, 3, 8]total = 0for price in prices: total += priceprint("Total:", total) for letter in "hey": print(letter)
Output
Press Run (⌘ Enter) to see what happens.

total += price is shorthand for total = total + price. The same works for -=, *= and the others.

Summing a list, one item per pass
4
0
10
1
3
2
8
3
total = 0

Before the loop, total starts at 0.

1/5

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.
Python
for i in range(3): print("Attempt", i + 1) print(list(range(2, 6)))print(list(range(10, 0, -3)))
Output
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.)

Predict the outputPython

What does this print?

for i in range(1, 10, 3):
  print(i)
Need a nudge? Hints walk you through it.

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.

Python
balance = 1000years = 0while balance < 2000: balance *= 1.07 # 7% growth per year years += 1print(f"Doubled after {years} years: {balance:.2f}")
Output
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.)

Quick check
Why does this loop never end?
i = 0
while i < 5:
  print(i)
Need a nudge? A hint rules out a wrong answer.

break, continue, and for...else

Two keywords change the flow inside any loop:

  • break leaves the loop immediately.
  • continue skips the rest of this pass and goes on to the next item.
Python
orders = [12, -1, 30, 0, 45, 999, 7]for amount in orders: if amount <= 0: continue # skip bad data if amount == 999: print("Sentinel found, stopping") break print("Processing", amount)
Output
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:

Python
users = ["sam", "leo", "priya"]target = "ada"for user in users: if user == target: print("Found", target) breakelse: print(target, "is not a user")
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

for n in [3, 5, 8, 9]:
  if n % 2 == 0:
      print("even:", n)
      break
else:
  print("no evens")
Need a nudge? Hints walk you through it.

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.

Python
names = ["Ada", "Sam", "Priya"]scores = [91, 78, 85] for i, name in enumerate(names, start=1): print(f"{i}. {name}") for name, score in zip(names, scores): print(f"{name}: {score}")
Output
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 the pairs0/5 matched

Match each task to the best tool.

Choose an item, then its match on the other side.

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:

Python
for row in range(1, 4): line = "" for col in range(1, 4): line += f"{row * col:4}" print(line)
Output
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.

One loop vs a loop inside a loop
input size n →ops
  • O(n)16
  • O(n²)256

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.

ChallengeEasy

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"]
Python
def fizzbuzz(n: int) -> list[str]: # Loop from 1 to n (inclusive) and build a list. pass
ChallengeEasy

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)
Python
def collatz_steps(n: int) -> int: # You do not know how many steps ahead of time. Which loop fits? pass
Key terms
iterable
Anything a for loop 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
break exits the loop now; continue skips to the next pass.
for...else
The else block runs only if the loop finished without break.
enumerate / zip
enumerate gives (index, item) pairs; zip walks 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.