Ravindra BagaleCourses & study guides मराठी Track your progress

Python if, elif and else Statements with Real Examples for Beginners

P5.2 How to Write if and else in Python

Why. You want different actions for different cases: send a reminder only if a bill is unpaid.

What. if condition: runs the indented lines below it only when the condition is True. else: runs when it is False. The colon and the 4-space indent are required.

How.

Write an if/else

  1. Write if, the condition and a colon.
  2. Indent the lines to run when True (4 spaces).
  3. Write else: at the same level as if.
  4. Indent the lines to run when False.
1. Check the condition2. True? → run the if block3. False? → run the else block4. Continue with the next line
How if / else decides (read from top to bottom)

Worked example A — A single if.

Step 1 — What we do. A bank in Toronto warns when the balance falls below $100.

Step 2 — Type and run this code.

balance = 75
if balance < 100:
    print("Low balance warning")

Step 3 — Output you should see.

Low balance warning

Step 4 — What it means. The condition is True, so the message prints. If balance were 500, nothing would print.

Worked example B — if with else.

Step 1 — What we do. A clinic checks if a patient is an adult.

Step 2 — Type and run this code.

age = 15
if age >= 18:
    print("Adult ward")
else:
    print("Children's ward")

Step 3 — Output you should see.

Children's ward

Step 4 — What it means. Exactly one of the two blocks runs. Here 15 is not >= 18, so the else block runs.

Worked example C — Use the decision to set a value.

Step 1 — What we do. We label an order as "Late" or "On time".

Step 2 — Type and run this code.

minutes = 42
if minutes > 30:
    status = "Late"
else:
    status = "On time"
print(status)

Step 3 — Output you should see.

Late

Step 4 — What it means. The decision fills a variable. In pandas you will create a whole status column with the same idea.

Python next to other languages — if / else. You do not need to learn these other languages. This only shows why Python is easier to read.

Language Code
Python if x > 30: (then indented lines)
Java if (x > 30) { ... } else { ... }
JavaScript if (x > 30) { ... } else { ... }
Go if x > 30 { ... } else { ... }

Ravindra Bagale's Tip

Python uses indentation instead of curly brackets. Always use 4 spaces. VS Code and Jupyter do it for you when you press Enter after a colon.