Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
Why Loops?For Loops BasicsWhile Loops BasicsLoop ControlIterating ListsLoop PatternsNested LoopsDebugging LoopsBest Practices
Python/Loops/Nested Loops

🏗️ Nested Loops — Loops Within Loops

Create complex patterns by placing one loop inside another.


🎯 Basic Concept

# 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: 1

💡 Creating Visual Patterns

Pattern 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:
# *
# **
# ***
# ****
# *****

🎨 Practical Applications

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

Example 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}")

⚠️ Breaking from Nested Loops

`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

🔑 Key Takeaways

ConceptRemember
IndentationInner loop indented more than outer
ExecutionInner loop runs completely for each outer iteration
breakOnly breaks innermost loop
ComplexityDoubles time with each nested loop

🔗 What's Next?

Troubleshoot loops with Debugging Loops!


Ready to practice? Challenges | Quiz


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn