
Python
Create complex patterns by placing one loop inside another.
# Outer loop runs 3 times
for i in range(3):
print(f"Outer: {i}")
# Inner loop runs 2 times for each outer iteration
for j in range(2):
print(f" Inner: {j}")Output:
Outer: 0
Inner: 0
Inner: 1
Outer: 1
Inner: 0
Inner: 1
Outer: 2
Inner: 0
Inner: 1Pattern 1: Rectangle of stars
for i in range(3): # 3 rows
for j in range(5): # 5 columns
print("*", end="")
print() # New line after each row
# Output:
# *****
# *****
# *****Pattern 2: Triangle
for i in range(1, 6): # i = 1, 2, 3, 4, 5
for j in range(i): # j loops i times
print("*", end="")
print()
# Output:
# *
# **
# ***
# ****
# *****Example 1: Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i}×{j}={i*j}", end=" ")
print()
# Output:
# 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=9Example 2: Search in grid
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
target = 5
for i in range(len(grid)): # Rows
for j in range(len(grid[i])): # Columns
if grid[i][j] == target:
print(f"Found {target} at row {i}, col {j}")`break` only breaks the innermost loop:
for i in range(3):
for j in range(3):
if j == 1:
break # Breaks inner loop only
print(j, end="")
print() # Still prints after break
# Output:
# 0
# 0
# 0| Concept | Remember |
|---|---|
| Indentation | Inner loop indented more than outer |
| Execution | Inner loop runs completely for each outer iteration |
| break | Only breaks innermost loop |
| Complexity | Doubles time with each nested loop |
Troubleshoot loops with Debugging Loops!
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward