How to Write Nested If Else in Python: Simple Guide
In Python, you write nested
if else statements by placing one if else block inside another. This lets you check multiple conditions step-by-step, using indentation to show the nesting.Syntax
A nested if else means putting one if else block inside another. The inner block runs only if the outer condition is true. Indentation shows which block belongs where.
- if condition: checks the first condition
- nested if condition: checks another condition inside the first
- else: runs if the
ifcondition is false
python
if condition1: if condition2: # code if both conditions are true else: # code if condition1 is true but condition2 is false else: # code if condition1 is false
Example
This example checks a number to see if it is positive, then if it is even or odd. It shows how nested if else helps check multiple things step-by-step.
python
number = 10 if number > 0: if number % 2 == 0: print("The number is positive and even.") else: print("The number is positive but odd.") else: print("The number is zero or negative.")
Output
The number is positive and even.
Common Pitfalls
Common mistakes include wrong indentation, which breaks the nesting, and forgetting to cover all cases with else. Also, too many nested levels can make code hard to read.
Here is a wrong and right way to write nested if else:
python
# Wrong: Missing indentation causes error # if x > 0: # if x < 10: # print("x is between 0 and 10") # Right: if x > 0: if x < 10: print("x is between 0 and 10")
Quick Reference
Remember these tips for nested if else in Python:
- Use indentation to show nesting clearly.
- Each
ifcan have its ownelse. - Keep nesting shallow for readability.
- Test all possible paths to avoid bugs.
Key Takeaways
Use indentation to nest
if else blocks inside each other in Python.Nested
if else lets you check multiple conditions step-by-step.Always include
else to handle cases when conditions are false.Avoid deep nesting to keep your code easy to read and maintain.
Test your nested conditions carefully to cover all possible cases.