Learn / Beginner / Lesson 10

Loops

12 min Tested on Python 3.15Updated By
In short

A for loop repeats code once for each item in a collection: for name in names:. A while loop repeats as long as a condition stays true. Use range() for counting, enumerate() when you also need the position, zip() to walk two lists together, and break or continue to leave or skip.

for loops

Python
cities = ["Pune", "Bangalore", "Brussels"]
for city in cities:
    print(f"Hello, {city}!")

for letter in "Py":
    print(letter)
Output
Hello, Pune!
Hello, Bangalore!
Hello, Brussels!
P
y

Counting with range()

Python
print(list(range(5)))
print(list(range(2, 6)))
print(list(range(10, 0, -3)))

total = 0
for n in range(1, 101):
    total += n
print(total)
Output
[0, 1, 2, 3, 4]
[2, 3, 4, 5]
[10, 7, 4, 1]
5050

range(stop) counts from 0 up to, but not including, stop. range(start, stop, step) gives full control.

enumerate() and zip()

Python
tasks = ["plan", "build", "test"]
for number, task in enumerate(tasks, start=1):
    print(number, task)

names = ["Ana", "Ben", "Cara"]
scores = [88, 92, 79]
for name, score in zip(names, scores):
    print(f"{name}: {score}")
Output
1 plan
2 build
3 test
Ana: 88
Ben: 92
Cara: 79

while loops

Python
balance = 1000
years = 0
while balance < 1500:
    balance *= 1.05
    years += 1
print(f"{years} years: {balance:.2f}")
Output
9 years: 1551.33

Use while when you don't know in advance how many repeats you need. Make sure something inside the loop eventually makes the condition false.

break and continue

Python
numbers = [4, 7, -1, 9, 12]
for n in numbers:
    if n < 0:
        print("Negative found, stopping")
        break
    print(n)

for n in range(1, 8):
    if n % 2 == 0:
        continue   # skip even numbers
    print(n, end=" ")
print()
Output
4
7
Negative found, stopping
1 3 5 7 

Loops inside loops

Python
for row in range(1, 4):
    line = ""
    for col in range(1, 4):
        line += f"{row * col:4}"
    print(line)
Output
   1   2   3
   2   4   6
   3   6   9

Practice

Classic FizzBuzz: for the numbers 1 to 15, print FizzBuzz if the number divides by both 3 and 5, Fizz if it divides by 3, Buzz if it divides by 5, and otherwise the number itself — one per line.

Expected output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
Your code

Quick check

1. What does list(range(3)) give?

2. What does continue do?

3. Best way to get each item and its position?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →