Loops: For and While
Published by Brayan K
A loop in Python is a control structure that repeats a block of code multiple times, using a for loop to iterate over a sequence or a while loop to repeat as long as a condition stays true.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
for: once for each item
A for loop runs its indented block once for each item of a sequence, with the loop variable set to that item. Text is a sequence of characters, and a list, a row of values in square brackets, is a sequence of values:
for letter in "abc":
print(letter)
for fruit in ["apple", "pear"]:
print("I like", fruit)
print("Done")
# ✅ Expected output:
# a
# b
# c
# I like apple
# I like pear
# DoneThe indented lines are the part that repeats. print("Done") isn't indented, so it runs once, after the second loop has finished. You choose the loop variable's name; pick one that says what each item is.
range(): counting, and the number it leaves out
To repeat something a number of times, loop over range(), which counts for you. Here list() turns each range into a list, so that print shows all of its numbers at once:
print(list(range(5)))
print(list(range(1, 6)))
print(list(range(0, 10, 2)))
print(list(range(5, 0, -1)))
# ✅ Expected output:
# [0, 1, 2, 3, 4]
# [1, 2, 3, 4, 5]
# [0, 2, 4, 6, 8]
# [5, 4, 3, 2, 1]range(5) starts at 0 and stops before 5, so it gives five numbers, 0 to 4. Every range leaves out its stop value, which is the classic off-by-one mistake: counting 1 to 5 takes range(1, 6). The third number is the step, and a negative step counts down, again stopping before the stop value.
To go through something backwards without working out a negative step, wrap it in reversed(). It hands the loop the items from last to first and leaves the list itself in its order:
names = ["Ada", "Ben", "Cy"]
for name in reversed(names):
print(name)
print(names)
print(list(reversed(range(1, 6))))
# ✅ Expected output:
# Cy
# Ben
# Ada
# ['Ada', 'Ben', 'Cy']
# [5, 4, 3, 2, 1]reversed(range(1, 6)) gives the same numbers as range(5, 0, -1), and it is easier to get right: write the range you'd count up with, then reverse it.
A number on its own has no items to go through, so it can't follow in:
for i in 5:
print(i)
# ✅ Expected error:
# TypeError: 'int' object is not iterable"Iterable" means something a for loop can go through. Write range(5) to get five numbers.
Inside the loop or after it
A running total shows why it matters where each line sits. The total starts before the loop, grows inside it, and is printed once after it:
total = 0
for price in [3, 5, 2]:
total = total + price
print("Total:", total)
# ✅ Expected output:
# Total: 10Move the first and last lines into the loop and the program means something else:
for price in [3, 5, 2]:
total = 0
total = total + price
print("Total:", total)
# ✅ Expected output:
# Total: 3
# Total: 5
# Total: 2total is reset to 0 every time round, and the print runs once per price. For each line, ask whether it should happen once per item, inside the loop, or once in all, before or after it.
After the loop, the loop variable still holds the last item it was given:
for n in range(3):
print("inside:", n)
print("after:", n)
# ✅ Expected output:
# inside: 0
# inside: 1
# inside: 2
# after: 2That's only true if the loop ran at least once. Over an empty sequence the block never runs, so the variable is never created:
for n in range(0):
print("inside:", n)
print("after:", n)
# ✅ Expected error:
# NameError: name 'n' is not definedwhile: repeat until something changes
A while loop repeats its block for as long as its condition is true. Python checks the condition before every round, the first one included:
count = 3
while count > 0:
print(count)
count = count - 1
print("Lift off")
# ✅ Expected output:
# 3
# 2
# 1
# Lift offSomething inside the loop has to move the condition towards false. Delete count = count - 1 and count stays 3, so the loop never ends. On your own computer, Ctrl+C stops a program stuck like that; this site's editor runs Python inside the page, so there an endless loop freezes the page until you close the tab.
Use while when you can't say in advance how many rounds it will take, such as how many years 7% interest takes to double 100:
balance = 100
years = 0
while balance < 200:
balance = balance * 1.07
years = years + 1
print(years, "years")
# ✅ Expected output:
# 11 yearsWhen you're going through the items of something, or repeating a number of times you know, use for. And when the place to stop is in the middle of the loop, as in a program that keeps asking until someone types quit, the usual shape is while True with a break, which the next section explains. Because input() waits for typing, this one is shown rather than run:
while True:
answer = input("Type a word, or quit: ")
if answer == "quit":
break
print("You typed", answer)break and continue
break leaves the loop at once. continue skips the rest of the current round and goes on to the next item:
for n in [4, 0, 7, -1, 9]:
if n == 0:
continue
if n < 0:
break
print(n)
print("after the loop")
# ✅ Expected output:
# 4
# 7
# after the loop0 is skipped, so it's never printed, and the loop goes on to 7. -1 ends the loop, so 9 is never reached, and Python carries on with the line after the loop.
A loop inside a loop, and which one break leaves
A loop's block can hold another loop. The inner loop runs all the way through for each round of the outer one:
for row in range(3):
for col in range(3):
if col == 2:
break
print(row, col)
print("done")
# ✅ Expected output:
# 0 0
# 0 1
# 1 0
# 1 1
# 2 0
# 2 1
# donebreak ends only the loop it's written in. Each time col reaches 2, the inner loop stops, but the outer loop carries on with the next row. To stop both at once, set a variable that the outer loop checks, or put the loops in a function and leave it with return, which Functions introduces.
else on a loop: when nothing broke out
A loop can have an else block, and it runs only when the loop ends without a break. It's how you say "I looked at every item and didn't find one":
for n in [3, 5, 9]:
if n % 2 == 0:
print("even:", n)
break
else:
print("no even number in the first list")
for n in [3, 4, 9]:
if n % 2 == 0:
print("even:", n)
break
else:
print("no even number in the second list")
# ✅ Expected output:
# no even number in the first list
# even: 4Read the else as "no break". The first loop goes through every number without breaking, so its else runs; the second breaks at 4, so its else is skipped. Without it, you'd set a variable such as found = False before the loop and check it after. while loops can have an else too, with the same rule.
Don't change a list while looping over it
numbers.remove(n) deletes n from a list. Doing that to the list the loop is going through skips items, with no error to warn you:
numbers = [1, -2, -3, 4]
for n in numbers:
if n < 0:
numbers.remove(n)
print(numbers)
# ✅ Expected output:
# [1, -3, 4]The loop moves through the list by position. When -2 is removed, everything after it moves one place left, so -3 lands in the place the loop has just checked, and the next round looks at 4. Loop over one list and build another instead; .append() adds an item to the end of a list:
numbers = [1, -2, -3, 4]
kept = []
for n in numbers:
if n >= 0:
kept.append(n)
print(kept)
# ✅ Expected output:
# [1, 4]Lists and Collections covers remove(), append() and the other ways to change a list.
Positions and pairs: enumerate() and zip()
Two built-in functions cover the commonest reasons to want more than one item at a time:
names = ["Ada", "Ben", "Cy"]
scores = [90, 72, 85]
for place, name in enumerate(names, start=1):
print(place, name)
for name, score in zip(names, scores):
print(name, score)
# ✅ Expected output:
# 1 Ada
# 2 Ben
# 3 Cy
# Ada 90
# Ben 72
# Cy 85enumerate() gives each item with its position, counting from start, or from 0 if you leave it out. zip() pairs up the items of two sequences and stops at the end of the shorter one. Each round gives a pair, so the for line names two variables, one for each half. enumerate & zip covers both in depth.
Practice: FizzBuzz up to 15
FizzBuzz counts from 1 to 15, printing Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both and the number itself otherwise. Fill the three blanks with the values in the hint lines, in order, and run it.
for n in range(1, ___):
if n % 15 == 0:
print("FizzBuzz")
___ n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
___:
print(n)
# 👉 replace ___ with 16
# 👉 replace ___ with elif
# 👉 replace ___ with else
# ✅ Expected output:
# 1
# 2
# Fizz
# 4
# Buzz
# Fizz
# 7
# 8
# Fizz
# Buzz
# 11
# Fizz
# 13
# 14
# FizzBuzzThe range stops at 16 so that 15 is included, and the test for 15 comes first because 15 is also a multiple of 3: tested after it, the Fizz branch would win.
On your own: the primes below 30
A prime is a whole number above 1 that only 1 and itself divide exactly. Print every prime below 30, one per line, by trying each number against every smaller number from 2 upwards and stopping at the first one that divides it. There are ten, from 2 to 29. Then compare with this solution:
for n in range(2, 30):
for d in range(2, n):
if n % d == 0:
break
else:
print(n)
# ✅ Expected output:
# 2
# 3
# 5
# 7
# 11
# 13
# 17
# 19
# 23
# 29The else belongs to the inner loop, so it runs only when no divisor broke out of it. For 2, range(2, 2) is empty: the inner loop ends at once without a break, and 2 is printed.
Practice quiz
What does print(list(range(2, 6))) show?
- [2, 3, 4, 5, 6]
- [2, 3, 4, 5]
- [3, 4, 5, 6]
- [2, 6]
Answer: [2, 3, 4, 5]. range starts at the first number and stops before the second, so 6 is left out.
After for n in range(3): print(n), what does one more print(n) after the loop show?
- 0
- 3
- 2
- An error
Answer: 2. The loop variable keeps the last value it was given, and range(3) ends at 2.
Which of these prints the numbers 1 to 5?
- for i in range(5): print(i)
- for i in range(1, 5): print(i)
- for i in range(0, 6): print(i)
- for i in range(1, 6): print(i)
Answer: for i in range(1, 6): print(i). The stop value is left out, so counting to 5 needs a stop of 6. range(5) gives 0 to 4.
In for n in [4, 0, 7]: with if n == 0: continue before print(n), what prints?
- 4 and 7
- 4 only
- 4, 0 and 7
- Nothing
Answer: 4 and 7. continue skips the rest of the round for 0, and the loop goes on to 7.
What does break inside an inner loop do?
- Ends both loops
- Ends only the inner loop
- Skips one round of the outer loop
- Stops the program with an error
Answer: Ends only the inner loop. break leaves the loop it's written in. The outer loop carries on with its next round.
When does the else block of a for loop run?
- Always, after the loop
- Only when the loop runs zero times
- When the loop finishes without a break
- When an error happens in the loop
Answer: When the loop finishes without a break. Read a loop's else as "no break". It also runs when the loop had nothing to go through.
count = 5, then while count > 0: count = count - 2. What is count after the loop?
- -1
- 0
- 1
- The loop never ends
Answer: -1. count goes 5, 3, 1, -1. The condition is checked before each round, and -1 > 0 is false.
numbers = [1, -2, -3, 4]. A for loop over numbers removes each negative n from numbers as it goes. What's left?
- [1, 4]
- [1, -3, 4]
- [1, -2, 4]
- An error
Answer: [1, -3, 4]. Removing -2 moves -3 into the place the loop has just checked, so the loop never sees it.
Continue this course
- Previous: Control Flow - If/Else
- Next: Functions — Write reusable blocks of code and pass data in and out with parameters
- Quick reference: Python cheat sheet › Loops & Iteration
- From the blog: The Two Things That Actually Confused Me Learning Python (That No Course Explains)
Frequently asked questions
Does Python have a do-while loop?
No. The usual replacement is while True: with an if and a break at the point where the loop should stop. The body then always runs at least once, which is what a do-while loop is for.
How do I stop a loop that never ends?
On your own computer, press Ctrl+C in the terminal, and Python stops the program with a KeyboardInterrupt. This site's editor runs Python inside the web page, so an endless loop there freezes the page: close the tab and open the editor again.