A nested if-else statement means placing an if or if-else statement inside another if or else block.
It is used when a decision depends on multiple conditions that are related to each other.
A nested if-else is:
An
if-elsestructure inside anotherif-elseblock to handle dependent conditions.
if condition1: if condition2: # code block else: # code blockelse: # code blockif condition is checkedif condition is evaluatedelse block executesnum = 10 if num > 0: if num % 2 == 0: print("Positive Even Number") else: print("Positive Odd Number")else: print("Number is not positive")Output
Positive Even Numbernum > 0 → Truenum % 2 == 0 → Trueusername = "admin"password = "1234" if username == "admin": if password == "1234": print("Login Successful") else: print("Incorrect Password")else: print("Invalid Username")a = 10b = 20 if a > b: print("A is greater")else: if b > a: print("B is greater") else: print("Both are equal")if and If-Else Ladder| Feature | Nested if | If-Else Ladder |
|---|---|---|
| Condition Type | Dependent | Independent |
| Structure | if inside if | Sequential |
| Readability | Can be complex | More readable |
if-else means placing one if inside another