AiTechWorlds
AiTechWorlds
Imagine a car manufacturing plant. There's a main conveyor belt — the outer loop — that carries car bodies through the factory, one after another. For each car body that comes along, there's a separate inspection station — the inner loop — that checks every individual component: engine, doors, windows, tires.
The outer belt moves when one car is fully inspected. The inner station runs for every part on that one car. Two levels of repetition, one inside the other.
That's exactly what nested loops are: a loop running inside another loop.
But factories also have emergency stops and skip mechanisms. If an inspector finds a critical defect, they can halt the entire line immediately. If a part is optional and missing, they can skip it and move on without stopping everything.
In Python, break is the emergency stop and continue is the skip mechanism.
Syntax:
for outer_variable in outer_sequence:
for inner_variable in inner_sequence:
# this runs for every combination
For each single iteration of the outer loop, the entire inner loop runs from start to finish.
Visual example — a 3×3 grid:
for row in range(1, 4):
for col in range(1, 4):
print(f"({row},{col})", end=" ")
print() # new line after each row
Output:
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)
The outer loop controls rows. The inner loop controls columns. Together they visit every cell in the grid.
A classic use of nested loops is generating a multiplication grid:
print(" ", end="")
for i in range(1, 6):
print(f"{i:4}", end="")
print()
print(" " + "----" * 5)
for i in range(1, 6):
print(f"{i:2} |", end="")
for j in range(1, 6):
print(f"{i*j:4}", end="")
print()
Output:
1 2 3 4 5
--------------------
1 | 1 2 3 4 5
2 | 2 4 6 8 10
3 | 3 6 9 12 15
4 | 4 8 12 16 20
5 | 5 10 15 20 25
Outer loop: each row (multiplier 1–5). Inner loop: each column (multiplicand 1–5). Each cell shows their product.
break: Exit the Loop Immediatelybreak stops the current loop entirely and jumps to the code after it. Think of it as pulling the emergency brake.
When to use it: You found what you were looking for. No point continuing.
numbers = [3, 7, 12, 5, 19, 8, 4]
for num in numbers:
if num > 10:
print(f"First number over 10: {num}")
break
Output:
First number over 10: 12
Without break, the loop would keep running even after finding the answer (wasting time and possibly printing wrong results).
Important: break only exits the innermost loop it's in. If you're in a nested loop, you need extra logic to break out of the outer loop too — which we'll see in the real example below.
continue: Skip This Iteration, Move to the Nextcontinue skips the rest of the current iteration and jumps straight to the next one. The loop doesn't stop — it just skips over unwanted items.
When to use it: Skip invalid, irrelevant, or already-processed items.
for i in range(1, 11):
if i % 2 == 0: # if even
continue
print(i)
Output:
1
3
5
7
9
Even numbers hit continue and their print is skipped. Odd numbers fall through to the print normally.
Another example — skipping empty entries:
names = ["Alice", "", "Bob", " ", "Charlie", ""]
for name in names:
if not name.strip(): # empty or whitespace-only
continue
print(f"Hello, {name}!")
Output:
Hello, Alice!
Hello, Bob!
Hello, Charlie!
else Clause on Loops (Python-Specific)Python has a unique feature: you can attach an else block to a loop. It runs only if the loop completed without hitting a break.
for i in range(1, 6):
if i == 10: # never true
break
else:
print("Loop finished normally — no break occurred")
Output:
Loop finished normally — no break occurred
This is useful for "search and not found" patterns — if break never fires, the item wasn't there.
A school has three classes, each with multiple students. You want to find which class a given student belongs to. The data is a list of lists — a 2D structure. Nested loops are the natural fit.
# Finding a student in class rolls
classes = [
["Alice", "Bob", "Charlie"],
["Diana", "Eve", "Frank"],
["Grace", "Henry", "Iris"]
]
search = input("Enter student name: ")
found = False
for class_num, students in enumerate(classes, 1):
for student in students:
if student.lower() == search.lower():
print(f"Found {student} in Class {class_num}")
found = True
break
if found:
break
if not found:
print(f"{search} not found")
What each part does:
enumerate(classes, 1) — loops over classes and gives each sublist a number starting at 1; returns (class_num, students) pairs.lower() on both sides — makes the search case-insensitive (matches "alice", "Alice", "ALICE")found = True + break — marks success and exits the inner loopif found: break — immediately exits the outer loop too (since inner break only stops the inner loop)if not found: — runs only if neither loop triggered a matchSample runs:
Enter student name: Eve
Found Eve in Class 2
Enter student name: henry
Found Henry in Class 3
Enter student name: Zara
Zara not found
| Feature | break | continue |
|---|---|---|
| Effect | Exits the loop entirely | Skips to next iteration |
| Loop continues? | No | Yes |
| Use when | You found what you need | You want to skip certain items |
| Analogy | Emergency stop button | "Skip this one" button |
Nested loops can be slow on large data sets. A loop with 1,000 iterations running inside another loop with 1,000 iterations = 1,000,000 total operations. This grows as O(n²) — doubling the data quadruples the work.
For small data (under a few thousand items), this is fine. For large data, you'd eventually look at more efficient data structures like dictionaries or sets that can find items in constant time. For now, understanding nested loops is the essential first step.
break exits the current loop immediately — useful when you've found your answercontinue skips the rest of the current iteration and moves to the next — useful for filteringbreak in an inner loop does not automatically break the outer loop — use a flag variable (found = True) to propagate the exitelse block runs only when no break occurred — handy for "not found" logicNext lesson: Functions — the most important tool for organizing and reusing your code.
Get this course's notes on Telegram!
Free cheat sheets, summaries & practice exercises