Python Nested Loops
## Python Nested Loops
In Python, a **nested loop** is a loop statement written inside another loop statement.
Python allows you to nest any type of loop inside any other type of loop. For instance, you can place a `for` loop inside another `for` loop, a `while` loop inside another `while` loop, or even mix them by putting a `while` loop inside a `for` loop (and vice versa).
---
## Syntax
### 1. Nested `for` Loop
The syntax for nesting a `for` loop inside another `for` loop is as follows:
```python
for outer_variable in outer_sequence:
for inner_variable in inner_sequence:
# Statements executed inside the inner loop
statement(s)
# Statements executed inside the outer loop
statement(s)
```
### 2. Nested `while` Loop
The syntax for nesting a `while` loop inside another `while` loop is as follows:
```python
while outer_expression:
while inner_expression:
# Statements executed inside the inner loop
statement(s)
# Statements executed inside the outer loop
statement(s)
```
> **Note:** You can nest loops to any depth you require. However, deep nesting (more than 2 or 3 levels) can make your code difficult to read, maintain, and debug.
---
## Code Examples
### Example 1: Finding Prime Numbers from 2 to 100
The following example uses nested `while` loops to find and print all prime numbers between 2 and 100.
```python
# Initialize the outer loop counter
i = 2
while i < 100:
# Initialize the inner loop divisor
j = 2
while j <= (i / j):
# If 'i' is divisible by 'j', it is not a prime number
if not (i % j):
break
j = j + 1
# If the loop finished without finding a divisor, 'i' is prime
if j > (i / j):
print(f"{i} is a prime number")
i = i + 1
print("Good bye!")
```
#### Output:
```text
2 is a prime number
3 is a prime number
5 is a prime number
7 is a prime number
11 is a prime number
13 is a prime number
17 is a prime number
19 is a prime number
23 is a prime number
29 is a prime number
31 is a prime number
37 is a prime number
41 is a prime number
43 is a prime number
47 is a prime number
53 is a prime number
59 is a prime number
61 is a prime number
67 is a prime number
71 is a prime number
73 is a prime number
79 is a prime number
83 is a prime number
89 is a prime number
97 is a prime number
Good bye!
```
---
### Example 2: Nested `for` Loop (Multiplication Table)
A classic use case for nested `for` loops is generating a grid or matrix, such as a multiplication table.
```python
# Outer loop for rows
for i in range(1, 10):
# Inner loop for columns
for j in range(1, i + 1):
print(f"{j}x{i}={i*j}", end="\t")
# Print a newline after each row completes
print()
```
#### Output:
```text
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
```
---
## Key Considerations
1. **Execution Flow:**
For every single iteration of the outer loop, the inner loop executes its entire cycle from start to finish. If the outer loop runs $M$ times and the inner loop runs $N$ times, the statements inside the inner loop will execute $M \times N$ times.
2. **Performance (Time Complexity):**
Nested loops increase the time complexity of your program. A double nested loop typically has a time complexity of $\mathcal{O}(n^2)$. Be cautious when using nested loops with large datasets, as it can significantly slow down execution.
3. **The `break` Statement in Nested Loops:**
If you use a `break` statement inside an inner loop, it will only terminate the **innermost** loop. The outer loop will continue to run its next iteration.
YouTip