Python Tutorial

Introduction

Edit Template
  • Home
  • /
  • Python Nested Loops

Python Tutorial

Introduction

Edit Template
  • Home
  • /
  • Python Nested Loops

Nested Loops in Python

Sometimes in programming, we need to use one loop inside another. This is called a nested loop.

You might use nested loops to build patterns, process data in layers, or create tables—like multiplication tables.

Example 1: while loop outside, for loop inside

Let’s say we want to print multiplication tables for 1 to 3. Here’s how you can do that using a while loop and a for loop:

				
					table = 1
while table <= 3:
    for num in range(1, 4):
        print(table, "x", num, "=", table * num)
    table += 1
    print()

				
			

Output:

				
					1 x 1 = 1
1 x 2 = 2
1 x 3 = 3

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6

3 x 1 = 3
3 x 2 = 6
3 x 3 = 9

				
			

In this example:

  • The while loop controls which table (1 to 3) to print.

  • The for loop handles numbers 1 to 3 for multiplication.

Example 2: for loop outside, while loop inside

Now let’s switch the structure. This time, the outer loop is a for loop, and the inner loop is a while loop:

				
					for table in range(1, 4):
    num = 1
    while num <= 3:
        print(table, "x", num, "=", table * num)
        num += 1
    print()

				
			

Output:

				
					1 x 1 = 1
1 x 2 = 2
1 x 3 = 3

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6

3 x 1 = 3
3 x 2 = 6
3 x 3 = 9

				
			

This example gives the same result, just using a different combination of loops.

Summary

Nested loops can be powerful, but they should be used carefully. If not managed properly, they can increase the complexity of your code and slow things down when working with large data.

Keep practicing and try building patterns or solving problems using nested loops to get comfortable with how they work.

Scroll to Top