Nested If

3 min read ·

A nested if statement means an if statement written inside another if statement.
It is used when:
  • One condition depends on another condition
  • You want to check a condition only if a previous condition is True

Syntax of Nested if

  • Outer if is checked first
  • Inner if is checked only if outer condition is True
  • Indentation is very important
Note

Every nested block must be properly indented.


Basic Nested if Example

  • First condition checks adulthood
  • Second condition checks working age

Nested if with Numbers


Nested if with else


Nested if with User Input


Nested if with Logical Conditions


Nested if vs Logical Operators

Using Nested if

Using Logical Operator

Pro Tip

Use logical operators when conditions are simple. Use nested if when logic depends on step-by-step checks.


Deep Nested if Example


Common Errors in Nested if

Wrong Indentation ❌

Missing Condition ❌

Stop

Most nested if errors happen due to indentation mistakes.


Real World Example – ATM Withdrawal

Real World Scenario

ATM checks before allowing withdrawal


Exercise

Practice Task
  1. Check if a number is positive and even using nested if
  2. Create a login system using username and password
  3. Take marks input and print Pass / Fail / Distinction using nested if
  4. Build an ATM logic using PIN and balance check