Lesson 6 of 34 · Fundamentals
Python Loops: for, range() and while
Computers shine at repetition. Instead of writing the same line a hundred times, you write a loop. Python has two kinds: the for loop, which walks through a sequence of values, and the while loop, which repeats as long as a condition stays true.
The for loop
A for loop takes each item of a sequence in turn. A string, for example, is a sequence of characters:
for letter in "hiss":
print(letter)
h
i
s
s
The indented block runs once per item, with letter holding the current character.
Counting with range()
range() produces a sequence of whole numbers — the most common way to loop a set number of times:
for i in range(3): # 0, 1, 2
print("Attack", i)
for n in range(1, 6): # 1, 2, 3, 4, 5
print(n)
for n in range(10, 0, -3): # 10, 7, 4, 1 (start, stop, step)
print(n)
The stop value is never included: range(1, 6) stops at 5. If you don't need the loop variable at all, name it _: for _ in range(3):.
The accumulator pattern
Many loops build up a result step by step: start with an empty or zero value, then update it on each pass.
total = 0
for n in range(1, 101):
total += n
print(total) # 5050
vowels = 0
for char in "serpent":
if char in "aeiou":
vowels += 1
print(vowels) # 2
The while loop
A while loop repeats as long as its condition is true. Use it when you don't know in advance how many repetitions you'll need:
gold = 1
days = 0
while gold < 100:
gold *= 2
days += 1
print(days) # 7
Something inside the loop must eventually make the condition false. Otherwise you get an infinite loop — here in the browser your run would stop with a timeout.
break and continue
breakleaves the loop immediately.continueskips the rest of the current pass and jumps to the next one.
for n in range(1, 10):
if n % 2 == 0:
continue # skip even numbers
if n > 5:
break # stop completely
print(n) # prints 1, 3, 5
A common pattern is while True: combined with a break once some goal is reached.
Common mistakes
- Off-by-one errors:
range(1, 10)stops at 9. To include 10, writerange(1, 11). - Forgetting to update the condition in a
whileloop, causing an infinite loop. - Wrong indentation: a
returnorprintindented inside the loop runs on every pass; dedent it to run once after the loop ends. - Using
/when you need whole numbers:n / 2produces a float; usen // 2to stay with integers.
Assignment
Write two loop-powered functions:
sum_multiples(limit)returns the sum of all numbers from 1 up to and includinglimitthat are divisible by 3 or 5. For examplesum_multiples(10)is3 + 5 + 6 + 9 + 10 = 33. Iflimitis less than 3, the sum is0.collatz_steps(n)counts how many steps it takes to reach 1 from a positive integernusing these rules: ifnis even, divide it by 2; if it's odd, replace it with3 * n + 1. Starting at 6: 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1, which is 8 steps.collatz_steps(1)is0.
Loops in other languages
- JavaScript Loops: for and while · JavaScript
- Go for Loops: The Only Loop You Need · Go
- Java Loops: for, while and do-while · Java
- C# Loops: for, while, do-while and foreach · C#
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .