Loops
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
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()
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()
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
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
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
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