if...elif...else Statements
You will choose which code runs by writing conditions with if, elif, and else.
Basic if statements
if condition:
do_this()
else:
do_that()
temperature = 28
if temperature > 30:
print('Hot day')
else:
print('Not a hot day')
temperature > 30 is false because 28 is not greater than 30. Python skips the indented if block and runs the else block instead.
Truthiness and elif
A condition is something Python can treat as true or false. Non-empty strings and non-zero numbers are truthy; empty strings, zero, and None are falsy. You can use these values directly in a condition.
score = 82
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'D'
print(grade)
print('has text' if 'go' else 'empty')
Python tests an if/elif chain from top to bottom and runs the first matching branch. The one-line conditional expression reads as: choose 'has text' if 'go' is truthy; otherwise choose 'empty'.
Nested conditions and match
member = True
age = 16
if member:
if age < 18:
print('Junior member')
else:
print('Adult member')
command = 'start'
match command:
case 'start':
print('Starting')
case 'stop':
print('Stopping')
case _:
print('Unknown command')
The second if runs only because member is true. The match statement compares one value with cases; the underscore case is a fallback when no earlier case matches.
Key points
- An if condition controls whether an indented block runs.
- Use elif to test another condition after if.
- else is the fallback when earlier conditions are false.
- Empty values and zero are falsy; many other values are truthy.
- A conditional expression makes a short two-way choice.
Worked example
Bangladesh pass mark is 33. Decide PASS or FAIL for a given mark.
mark = 61
if mark >= 33:
print("PASS")
else:
print("FAIL")
How it works, step by step
- The condition mark >= 33 is True (61 is bigger).
- So the if-block runs and the else-block is skipped.
- Indentation (4 spaces) defines which lines belong to which block.
References & Further Reading
Related entries from PyLabs's own reference library.
Practice exercise
Not passed yetSet number to 7. Use an if/else statement to print odd when the number has a remainder of 1 after division by 2; otherwise print even.
Expected output:
odd
# Write your code below
Check yourself
if...elif...else Statements quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.