Python From Beginner to Advanced

0% completed

Previous
Next
Python - Nested if Statement

A nested if statement is an if statement inside another if statement. It allows checking multiple conditions in a structured way. The inner if block runs only if the outer if condition is True. This is useful when one condition depends on another before executing a block of code.

Syntax

if condition1: if condition2: # Code executes if both condition1 and condition2 are True else: # Code executes if condition1 is True but condition2 is False else: # Code executes if condition1 is False
  • The outer if is checked first.
  • If True, the inner if is evaluated.
  • If the inner condition is True, its block runs; otherwise, the else block under it executes.
  • If the outer if is False, the entire inner block is skipped.

Examples

Example 1: Checking Eligibility for a Driving License

Python3
Python3

. . . .

Explanation

  1. The variable age is 20, and has_license is True.
  2. The outer if age >= 18 is True, so Python checks the inner if has_license.
  3. Since has_license is True, the program prints:
    You can drive.
    
  4. If has_license were False, the inner else would run, printing:
    You need a driving license.
    
  5. If age were less than 18, the outer else would execute.

Example 2: Checking Exam Result with Distinction

Python3
Python3

. . . .

Explanation

  1. The variable marks is 85.
  2. The outer if marks >= 50 is True, so "You passed the exam." is printed.
  3. The inner if marks >= 80 is also True, so "You passed with distinction!" is printed.
  4. If marks were 60, only "You passed the exam." would be printed.
  5. If marks were below 50, the outer else would run, printing "You failed the exam."

A nested if statement helps check conditions that depend on previous conditions. The outer if must be True for the inner if to execute. This structure is useful in real-world situations like verifying eligibility, granting permissions, or checking multiple conditions step by step.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next