Python Mastery – From Basics to Brilliance / Control Flow & Decision Making

Nested Conditions & Loops

πŸ”Ή Nested Conditions

A condition inside another condition is called a nested condition.

age = 20
has_id = True

if age >= 18:
    if has_id:
        print("Entry allowed")

Here, the second if is inside the first if.

You can also use else:

age = 16

if age >= 18:
    if age >= 21:
        print("Eligible")
    else:
        print("Between 18 and 20")
else:
    print("Under 18")

πŸ” Nested Loops

A loop inside another loop is called a nested loop.

for i in range(3):
    for j in range(2):
        print(i, j)
0 0
0 1
1 0
1 1
2 0
2 1

The inner loop completes all its iterations for every iteration of the outer loop.

Outer Loop
   ↓
i = 0 β†’ j = 0, 1
i = 1 β†’ j = 0, 1
i = 2 β†’ j = 0, 1

🧩 Nested if Inside a Loop

Conditions and loops can also be combined.

for i in range(1, 6):
    if i % 2 == 0:
        print(i, "is even")
2 is even
4 is even

⭐ Remember

Nested Condition       β†’ if inside another if

Nested Loop            β†’ loop inside another loop

Nested Code            β†’ one block of code inside another