Python course menu
Python Loops: for and while Explained for Beginners
Learn Python for loops and while loops with simple examples. Loop over lists and strings, use range(), stop early with break, skip with continue, and avoid infinite loops.
On this page
Computers are brilliant at doing the same thing many times without getting bored. A loop repeats a block of code. Python has two kinds:
- a
forloop repeats once for each item in a collection, or a fixed number of times; - a
whileloop repeats for as long as a condition stays true.
The for loop#
for item in collection:
# code to repeatEach time around the loop (each iteration), the variable item holds the next value from the collection. The indented lines are the loop body.
cities = ["Mumbai", "Delhi", "Pune"]
for city in cities:
print(f"Shipping to {city}")
print("All done")Shipping to Mumbai
Shipping to Delhi
Shipping to Pune
All doneprint("All done") is not indented, so it is outside the loop and runs once, after the loop finishes.
Looping over a string#
A string is a sequence of characters, so you can loop over it too:
for letter in "code":
print(letter.upper())C
O
D
ERepeating a set number of times with range()#
range() produces a sequence of numbers, which makes it perfect for "do this N times":
for i in range(3):
print("Attempt", i)Attempt 0
Attempt 1
Attempt 2range(3) gives 0, 1, 2. It starts at 0 and stops before the number you give it, just like list slicing. You can also give a start, a stop, and a step:
Keeping a running total#
Loops are often used to build up a result step by step. Create the variable before the loop, then update it inside:
prices = [120, 80, 45, 300]
total = 0
for price in prices:
total += price
print(f"Total: {total}")Total: 545(Python's built-in sum(prices) does the same thing, but this pattern works for anything, not just adding.)
The while loop#
A while loop keeps running as long as its condition is True. Use it when you do not know in advance how many repetitions you need.
balance = 1000
years = 0
while balance < 2000:
balance = balance * 1.10 # grows 10% per year
years += 1
print(f"It takes {years} years to double")It takes 8 years to doubleEvery while loop needs three things:
- A variable the condition depends on (
balance). - A condition that is checked before each iteration (
balance < 2000). - Something inside the loop that changes that variable, so the condition eventually becomes
False.
Stopping early with break#
break exits the loop immediately, skipping any remaining items:
numbers = [4, 9, 15, 22, 7]
for n in numbers:
if n > 10:
print(f"First number over 10: {n}")
breakFirst number over 10: 15Skipping one item with continue#
continue skips the rest of the current iteration and jumps to the next one:
for n in range(1, 8):
if n % 2 == 0:
continue # skip even numbers
print(n)1
3
5
7while True with break#
A common pattern for "keep asking until we get a valid answer":
while True:
answer = input("Type yes or no: ").strip().lower()
if answer in ("yes", "no"):
break
print("Please type yes or no.")
print(f"You chose {answer}")The loop has no natural end, so break is the only way out. This is fine as long as the break is reachable.
Which loop should I use?#
In everyday Python, for loops are far more common.
Common mistakes#
Practice#
Practice exercise
Write a program that prints the multiplication table of 7 from 7 x 1 to 7 x 10, then prints the sum of all ten results.
Expected output starts like this:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21Show hint
Use for i in range(1, 11):. Keep a total variable outside the loop and add each result to it.
Show solution
number = 7
total = 0
for i in range(1, 11):
result = number * i
print(f"{number} x {i} = {result}")
total += result
print("Sum:", total)7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
Sum: 385The sum is 7 × (1 + 2 + … + 10) = 7 × 55 = 385.
Key takeaway#
Finished this lesson?