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
- Write
if, the condition and a colon. - Indent the lines to run when True (4 spaces).
- Write
else:at the same level asif. - Indent the lines to run when False.
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.
Ravindra Bagale's Tip – मराठी
Python curly brackets ऐवजी indentation वापरतो. नेहमी 4 spaces वापरा. Colon नंतर Enter दाबल्यावर VS Code आणि Jupyter हे आपोआप करतात.
Ravindra Bagale's Tip – हिंदी
Python curly brackets की जगह indentation इस्तेमाल करता है. हमेशा 4 spaces रखो. Colon के बाद Enter दबाने पर VS Code और Jupyter ये अपने आप करते हैं.