Skip to content
Laviyx Learn

Try

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.

Beginner9 min readUpdated
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 for loop repeats once for each item in a collection, or a fixed number of times;
  • a while loop repeats for as long as a condition stays true.

The for loop#

Python
for item in collection:
    # code to repeat

Each time around the loop (each iteration), the variable item holds the next value from the collection. The indented lines are the loop body.

Python
cities = ["Mumbai", "Delhi", "Pune"]

for city in cities:
    print(f"Shipping to {city}")

print("All done")
Output
Shipping to Mumbai
Shipping to Delhi
Shipping to Pune
All done

print("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:

Python
for letter in "code":
    print(letter.upper())
Output
C
O
D
E

Repeating a set number of times with range()#

range() produces a sequence of numbers, which makes it perfect for "do this N times":

Python
for i in range(3):
    print("Attempt", i)
Output
Attempt 0
Attempt 1
Attempt 2

range(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:

CallNumbers produced
range(5)0, 1, 2, 3, 4
range(1, 6)1, 2, 3, 4, 5
range(0, 10, 2)0, 2, 4, 6, 8
range(5, 0, -1)5, 4, 3, 2, 1

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:

Python
prices = [120, 80, 45, 300]
total = 0

for price in prices:
    total += price

print(f"Total: {total}")
Output
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.

Python
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")
Output
It takes 8 years to double

Every while loop needs three things:

  1. A variable the condition depends on (balance).
  2. A condition that is checked before each iteration (balance < 2000).
  3. 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:

Python
numbers = [4, 9, 15, 22, 7]

for n in numbers:
    if n > 10:
        print(f"First number over 10: {n}")
        break
Output
First number over 10: 15

Skipping one item with continue#

continue skips the rest of the current iteration and jumps to the next one:

Python
for n in range(1, 8):
    if n % 2 == 0:
        continue      # skip even numbers
    print(n)
Output
1
3
5
7

while True with break#

A common pattern for "keep asking until we get a valid answer":

Python
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?#

Use a for loop when…Use a while loop when…
you are going through a list, string, or other collectionyou repeat until something happens
you know how many times to repeatyou do not know how many repetitions you need
e.g. "for every student, print the grade"e.g. "keep asking until the password is correct"

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:

Output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
Show hint

Use for i in range(1, 11):. Keep a total variable outside the loop and add each result to it.

Show solution
Python
number = 7
total = 0

for i in range(1, 11):
    result = number * i
    print(f"{number} x {i} = {result}")
    total += result

print("Sum:", total)
Output
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: 385

The sum is 7 × (1 + 2 + … + 10) = 7 × 55 = 385.

Key takeaway#

Finished this lesson?