What You Will Learn
Intermediate
- How nested loops work
- Building patterns with loops
- Processing 2D data
Terminalpython
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
# 1x1=1, 1x2=2, 1x3=3
# 2x1=2, 2x2=4, 2x3=6
# 3x1=3, 3x2=6, 3x3=9Building a Star Pattern
Terminalpython
# Right triangle of stars
for i in range(1, 6):
for j in range(i):
print("*", end="")
print()
# *
# **
# ***
# ****
# *****Processing 2D Data (Grids)
Terminalpython
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in grid:
for cell in row:
print(cell, end=" ")
print()
# 1 2 3
# 4 5 6
# 7 8 9Nested loop complexity
Nested loops multiply iterations. A loop of 100 inside a loop of 100 = 10,000 iterations. Be careful with large data.Practical Exercise
Print a 3x3 grid of numbers using nested loops
Print a right triangle of stars (5 rows)
Print a multiplication table 1-5
Calculate the sum of all numbers in a 2D grid
Key Takeaways
- Nested loops = loop inside a loop.
- Inner loop completes for each iteration of outer loop.
- Complexity multiplies: O(n*m) for two loops.
- Common uses: patterns, 2D grids, matrices.
- Avoid deep nesting (3+ levels) - use functions instead.
Comments
Comments
Post a Comment