Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Loops Module 2 - Control Flow Python Python Basics Python Programming: From Zero to Real-World Applications

Nested Loops and Loop Patterns in Python

Reviewed & accurate
AI Summary

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=9

Building 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 9
Nested 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.
Previously: Lesson 14 covered range/enumerate.
Today: You learned: Loops inside loops - patterns and 2D data.
Next: Module 2 complete! Module 3 begins with lesson 16.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments