Nested if
- Python course
- Beginner
- Lesson 38/116
- 4 min
Learn nested if blocks.
Nested if
You can put another if inside an if block. This is called a nested if:
age = 25
has_id = True
if age >= 18:
if has_id:
print("Can enter")Nested ifs make logic explicit but get unreadable when deep. Combining two conditions with and is usually cleaner: if age >= 18 and has_id:
Nested if vs and
The same logic can be written two ways:
# Nested if
if age >= 18:
if has_id:
print("OK")
# with and
if age >= 18 and has_id:
print("OK")The and version is shorter and more readable. Nested if is preferred only when the second condition depends on the first and other code goes between.
Practice Print a condition with and
Assign age = 20 and has_id = True. Write if age >= 18 and has_id: print("Can enter").
Starter code
# Condition with andSample solution
age = 20
has_id = True
if age >= 18 and has_id:
print("Can enter")Expected output
Can enter
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Combine two conditions
if age >= 18 ____ has_id:
print("Can enter")
if age >= 18 and has_id:
print("Can enter")
Explanation: and gives True when both conditions are True.
2 What is preferred over nested if?
- Combining with and Correct answer
- Deeper nesting
- Splitting with else
- A while loop
Explanation: Combining with and is cleaner and more readable.
3 Match the condition forms
| Term | Meaning |
|---|---|
nested if |
Two if blocks |
and |
One if, two conditions |
or |
At least one True |
not |
Flips |