Nested Loops in Python

A nested loop is a loop placed inside another loop. The inner loop runs completely for each iteration of the outer loop.

🔁 Commonly used for patterns, tables, and matrices.

Basic Nested Loop Example

for i in range(1, 4):
    for j in range(1, 4):
        print(i, j)

Pattern Printing Example

Printing a square star pattern:

for i in range(4):
    for j in range(4):
        print("*", end=" ")
    print()

Multiplication Table

Using nested loops to print tables from 1 to 5:

for i in range(1, 6):
    for j in range(1, 11):
        print(i * j, end=" ")
    print()

Nested while Loop

i = 1
while i <= 3:
    j = 1
    while j <= 3:
        print(i, j)
        j += 1
    i += 1
❌ Nested loops may slow down programs if used unnecessarily.

Practice

  1. Print a right-angle triangle pattern
  2. Print tables from 1 to 10
  3. Print all coordinate pairs from (1,1) to (3,3)