Python

nested loops in Python

Click for All Topics

nested loops in Python

Definition: A nested loop is a programming concept where one loop is placed inside another loop.

NESTED loop statements:

It’s like putting one loop inside another loop. It’s like doing a task repeatedly within another task. The inner loop runs completely each time the outer loop runs once.

Various types of nested loops:

  1. Nested for loop:

A nested for loop is like putting one for loop inside another. It’s a way to do something repeatedly within another repeated action.

Example –

				
					# Example 1: Multiplication Table
for i in range(1, 6):  # Outer loop
    for j in range(1, 11):  # Inner loop
        product = i * j
        print(f"{i} * {j} = {product}")
    print()  # Add a newline after each table

# Output -
# 1 * 1 = 1
# 1 * 2 = 2
# 1 * 3 = 3
# 1 * 4 = 4
# 1 * 5 = 5
# 1 * 6 = 6
# 1 * 7 = 7
# 1 * 8 = 8
# 1 * 9 = 9
# 1 * 10 = 10

# 2 * 1 = 2
# 2 * 2 = 4
# 2 * 3 = 6
# 2 * 4 = 8
# 2 * 5 = 10
# 2 * 6 = 12
# 2 * 7 = 14
# 2 * 8 = 16
# 2 * 9 = 18
# 2 * 10 = 20

# 3 * 1 = 3
# 3 * 2 = 6
# 3 * 3 = 9
# 3 * 4 = 12
# 3 * 5 = 15
# 3 * 6 = 18
# 3 * 7 = 21
# 3 * 8 = 24
# 3 * 9 = 27
# 3 * 10 = 30

# 4 * 1 = 4
# 4 * 2 = 8
# 4 * 3 = 12
# 4 * 4 = 16
# 4 * 5 = 20
# 4 * 6 = 24
# 4 * 7 = 28
# 4 * 8 = 32
# 4 * 9 = 36
# 4 * 10 = 40

# 5 * 1 = 5
# 5 * 2 = 10
# 5 * 3 = 15
# 5 * 4 = 20
# 5 * 5 = 25
# 5 * 6 = 30
# 5 * 7 = 35
# 5 * 8 = 40
# 5 * 9 = 45
# 5 * 10 = 50
				
			
				
					# Example 2: 2D Array

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:  # Outer loop iterates over rows
    for element in row:  # Inner loop iterates over elements in each row
        print(element, end=" ")
    print()  # Move to the next row

# Output -
# 1 2 3 
# 4 5 6 
# 7 8 9 
				
			

One important use of nested for loops is to print patterns.

				
					# Example 3: Pattern Printing
for i in range(5):  # Outer loop for rows
    for j in range(i + 1):  # Inner loop for columns in each row
        print("*", end=" ")
    print()  # Move to the next row

# Output -
# * 
# * * 
# * * * 
# * * * * 
# * * * * * 
				
			
  1. Nested if:

Nested-if statements are useful when you need to handle complex branching logic, where certain conditions must be met before others can be evaluated

				
					# Example: Nested If Statements
x = 10
y = 5

if x > y:
    print("x is greater than y")
    if x > 7:
        print("x is also greater than 7")
else:
    print("x is not greater than y")

# Output -
# x is greater than y
# x is also greater than 7
				
			
				
					# Example 2: Grading System
score = 85

if score >= 90:
    print("You got an A!")
elif score >= 80:
    print("You got a B.")
    if score >= 85:
        print("You are close to an A.")
else:
    print("You need to improve.")

# Output -
# You got a B.
# You are close to an A.
				
			
				
					# Example 3: Divisibility Check
number = 15

if number % 2 == 0:
    print("The number is even.")
    if number % 3 == 0:
        print("The number is also divisible by 3.")
else:
    print("The number is odd.")

# Output -
# The number is odd.
				
			
  1. Nested while:

A nested while loop is like putting one while loop inside another. The inner while loop runs completely each time the outer while loop runs once.

Example –

				
					row = 1

while row <= 3:  # Outer loop for rows
    column = 1

    while column <= 4:  # Inner loop for columns
        print("Row", row, "Column", column)
        column += 1

    row += 1

# Output -
# Row 1 Column 1
# Row 1 Column 2
# Row 1 Column 3
# Row 1 Column 4
# Row 2 Column 1
# Row 2 Column 2
# Row 2 Column 3
# Row 2 Column 4
# Row 3 Column 1
# Row 3 Column 2
# Row 3 Column 3
# Row 3 Column 4
				
			

In this example,

  • The outer loop represents rows, and the inner loop represents columns. The code will print combinations of row and column numbers.
  • The outer loop runs three times for three rows, and the inner loop runs four times for four columns in each row.