Nearby lessons

44 of 159

Python - Nested Loops

📌 What You Will Learn
  • Define nested loops and how one loop sits inside another
  • Explain that the inner loop runs fully for every iteration of the outer loop
  • Write nested for loops to print patterns and matrices
  • Create a multiplication table using nested loops
  • Compare a single loop with a nested loop

What Are Nested Loops?

Nested loops mean placing one loop inside another loop.

The inner loop runs fully for each outer loop iteration.

Why Use Them?

Nested loops are useful for pattern printing, matrix processing, and table generation.

Syntax

🐍Code Cell
1for variable1 in sequence1:
2 for variable2 in sequence2:
3 statement
Output
No output captured.

Example 1 - Nested Loop

🐍Code Cell
1for i in range(3):
2 for j in range(3):
3 print("i =", i, "j =", j)
Output
i = 0 j = 0
i = 0 j = 1
i = 0 j = 2
i = 1 j = 0
i = 1 j = 1
i = 1 j = 2
i = 2 j = 0
i = 2 j = 1
i = 2 j = 2

Understanding Nested Loop

For every value of i, the inner loop runs completely.

After the inner loop finishes, the outer loop moves to the next value.

Example 2 - Print Rectangle Pattern

🐍Code Cell
1for i in range(4):
2 for j in range(5):
3 print("*", end=" ")
4 print()
Output
* * * * *
* * * * *
* * * * *
* * * * *

Example 3 - Multiplication Table

🐍Code Cell
1for i in range(1, 6):
2 for j in range(1, 6):
3 print(i * j, end=" ")
4 print()
Output
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

Difference Between Single Loop and Nested Loop

Single Loop Nested Loop
Contains only one loop. Contains one loop inside another loop.
Less repetition. More repetition.
Simple iteration. Useful for tables, matrices, and patterns.
📝 Key Takeaways
  • Nested loops place one loop inside another loop
  • The inner loop runs completely for each iteration of the outer loop
  • Nested loops are used for pattern printing, matrices and table generation
  • A multiplication table prints the product of every row and column pair
  • A single loop does simple iteration while a nested loop handles tables and patterns

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3