Account
Categories

Nested if statement


Definition:

When an if inside another if is called the nested if statement, in which if the first condition is met (true), then the code inside the outer if will execute.

If the outer condition is true, then the inner if condition is checked.

If the inner condition is also true, the code inside the inner if block will execute.

Otherwise, the code inside the else part will execute.

Now you will clearly understand the code logic by the flowchart.

Nested if Flowchart:

First step: → You write the program (marks = 70)
   ↓
Second step: → Check first condition (marks ≥ 50)
➡ If YES
   ↓
Check second condition (marks ≥ 60)
➡ If YES
   ↓
  Print "You passed with good marks."
➡ If NO
   ↓
  Print "You just passed."
➡ If NO (marks < 50)
   ↓
  Print "You failed."
   ↓
 End the program

Syntax:

if condition1:
    if condition2:
        code

Example:

marks = 70

if marks >= 50:
    if marks >= 60:
        print("You passed with good marks")
    else:
        print("You just passed")
else:
    print("You failed")

Output:

Exercise

Write a Python program using nested if for marks = 72.
If marks >= 50 check:
  ✔ If marks >= 80 → print "Excellent"
  ✔ Else → print "Good"