Definition
How does an app decide your grade from your marks?
A conditional statement runs a block of code only when a condition is True. if checks the first condition, elif checks further conditions in order, and else runs when none of them are True. Only the first matching branch runs. Conditions can be nested inside each other.
In simple words
It's the diamond in a flowchart, written in Python. if marks >= 90, the grade is A; elif marks >= 75, it's B; and so on, ending with else for everything else. Python checks from the top and stops at the first True.
Why it matters
Programs must react differently to different situations: approve or decline a payment, show or hide a message, label an email spam or not. Even the simplest AI, a rule-based chatbot, is built from conditions.
How it works
if marks >= 90:
grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 40:
grade = "C"
else:
grade = "Fail"- Each condition ends with a colon, and its block is indented.
- Order matters: put the most specific or highest check first.
- Combine conditions with and, or and not.
In code
The same grading rule applied to several marks, plus a nested check.
def grade(marks):
if marks >= 90:
return "A"
elif marks >= 75:
return "B"
elif marks >= 40:
return "C"
else:
return "Fail"
for marks in [95, 82, 40, 39]:
print(marks, "->", grade(marks))
age, has_ticket = 16, True
if has_ticket:
if age >= 18:
print("Enter the adult section")
else:
print("Enter the family section")
else:
print("Please buy a ticket")Output
95 -> A 82 -> B 40 -> C 39 -> Fail Enter the family section
Try it yourself
Which branch runs?
Using the grading rule above, which grade does each mark get?
marks = 12
marks = 75
marks = 90
marks = 40
marks = 89
Common mistakes
- Putting the lowest check first, so every mark above 40 gets C.
- Forgetting the colon or the indentation.
- Using = instead of == inside a condition.
Check yourself
Summary
- if, elif and else choose one branch to run.
- Python checks from the top and stops at the first True.
- Order the checks carefully, and indent each block.
Finished reading?
Sources: W3Schools: Python If...Else