πΉ 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 1The 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