In Python (programming language), a nested loop is a loop inside another loop. The inner loop runs completely for each iteration of the outer loop.
Nested loops are commonly used for tasks such as working with tables, matrices, patterns, or multi-dimensional data.
πΉ Basic Structure of Nested Loops
for outer_variable in sequence:
for inner_variable in sequence:
# code to execute
The inner loop executes fully each time the outer loop runs.
πΉ Example: Nested for Loop
for i in range(3):
for j in range(2):
print("i =", i, "j =", j)
Output:
i = 0 j = 0
i = 0 j = 1
i = 1 j = 0
i = 1 j = 1
i = 2 j = 0
i = 2 j = 1
Here:
- The outer loop runs 3 times
- The inner loop runs 2 times for each outer loop iteration
πΉ Example: Nested while Loop
i = 1while i <= 3:
j = 1
while j <= 2:
print(i, j)
j += 1
i += 1
Output:
1 1
1 2
2 1
2 2
3 1
3 2
πΉ Pattern Printing Example
Nested loops are often used to create patterns.
for i in range(5):
for j in range(5):
print("*", end=" ")
print()
Output:
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
πΉ Triangle Pattern Example
for i in range(1, 6):
for j in range(i):
print("*", end=" ")
print()
Output:
*
* *
* * *
* * * *
* * * * *
β Key Points
- A nested loop is a loop inside another loop.
- The inner loop runs completely for each iteration of the outer loop.
- Nested loops are used for:
- pattern printing
- working with tables or grids
- multi-dimensional data structures