The for Loop
Iterates over any iterable (list, string, range, dict, etc.):
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterate over a string
for char in "Python":
print(char)
# Iterate with range
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 10, 2): # start, stop, step
print(i) # 2, 4, 6, 8
range() in Detail
range(5) # 0 to 4
range(1, 6) # 1 to 5
range(0, 10, 2) # 0, 2, 4, 6, 8
range(5, 0, -1) # 5, 4, 3, 2, 1 (countdown)
# Convert to list to see values:
print(list(range(5))) # [0, 1, 2, 3, 4]
The while Loop
Runs while a condition is True:
count = 0
while count < 5:
print(count)
count += 1
# Infinite loop with break
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == "quit":
break
print(f"You entered: {user_input}")
break and continue
# break โ exit the loop entirely
for i in range(10):
if i == 5:
break
print(i) # 0, 1, 2, 3, 4
# continue โ skip to next iteration
for i in range(10):
if i % 2 == 0:
continue
print(i) # 1, 3, 5, 7, 9
else Clause on Loops
The else block runs if the loop completed without hitting break:
# Search for a value
numbers = [1, 3, 7, 9]
target = 5
for n in numbers:
if n == target:
print("Found!")
break
else:
print("Not found") # runs because break was never hit
Nested Loops
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i}ร{j}={i*j}", end=" ")
print()
# 1ร1=1 1ร2=2 1ร3=3
# 2ร1=2 2ร2=4 2ร3=6
# 3ร1=3 3ร2=6 3ร3=9
Useful Iteration Patterns
# enumerate โ get index and value
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# enumerate with start index
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
# zip โ iterate multiple iterables together
names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# zip_longest from itertools:
from itertools import zip_longest
for a, b in zip_longest([1, 2, 3], ["a", "b"], fillvalue=None):
print(a, b)
Exercises
Exercise 1: Sum of Squares
Calculate the sum of squares of numbers 1 to 10.
Solution:
total = 0
for i in range(1, 11):
total += i ** 2
print(total) # 385
Exercise 2: Countdown with while
Print a countdown from 10 to 1, then print "Blast off!"
Solution:
n = 10
while n > 0:
print(n)
n -= 1
print("Blast off!")
Exercise 3: Prime Numbers
Find all prime numbers between 2 and 50 using nested loops.
Solution:
primes = []
for n in range(2, 51):
for divisor in range(2, int(n**0.5) + 1):
if n % divisor == 0:
break
else:
primes.append(n)
print(primes)
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Exercise 4: Pattern Printing
Print this triangle pattern using nested loops:
*
**
***
****
*****
Solution:
for i in range(1, 6):
print("*" * i)
Exercise 5: Digit Sum
Find the sum of digits of the number 9876543210 using a loop.
Solution:
number = 9876543210
digit_sum = sum(int(d) for d in str(number))
print(digit_sum) # 45
# Alternative with while:
n = 9876543210
total = 0
while n > 0:
total += n % 10
n //= 10
print(total) # 45