Nested Loops & Loop else
Nested loops
A loop inside a loop: the inner loop runs completely for every round of the outer loop. They're useful for grids, tables and comparing every pair of items. Watch the cost: two nested loops over n items do n × n steps.
break only exits one level
break leaves the innermost loop only. To stop everything, move the loops into a function and return, or use a flag.
The loop else clause (unique to Python)
A for or while loop can have an else block that runs only if the loop finished without break. Think of it as "no break happened":
for item in items:
if item == target:
print("found")
break
else:
print("not found")
It's perfect for searching, such as checking whether a number is prime.
💡 Checking divisors only up to √n makes the prime check much faster.
▶️ Runs in the app.
Example
# Multiplication table (nested loops)
for i in range(1, 4):
for j in range(1, 4):
print(f"{i*j:3}", end="")
print()
# 1 2 3
# 2 4 6
# 3 6 9
# Primes with for-else
for n in range(2, 20):
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
break # n has a divisor → not prime
else:
print(n, end=" ") # runs only when no break happened
print() # 2 3 5 7 11 13 17 19