Making Decisions with if/elif/else
1 min read3 lessons in topic
Learning objective
By the end of this lesson you will be able to write programs that choose between actions based on conditions.
Programs make decisions all the time. Python's if statement runs a block of code only when a condition is true.
The if statement
score = 75
if score >= 50:
print("You passed!")Indentation (4 spaces) tells Python which lines belong to the if block.
elif and else
score = 85
if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
elif score >= 50:
grade = "C"
else:
grade = "F"
print("Grade:", grade)Combining conditions
age = 20
has_id = True
if age >= 18 and has_id:
print("Entry allowed")- == equal
- != not equal
- > < greater / less than
- and / or — combine conditions
- not — negate a condition
Code playground
Run and edit the starter code — experiment freely.
python · runnable
Output appears here when you press Run.
Practice exercise
Write a program that reads a temperature and prints Hot, Warm, Cool or Cold.
Check your understanding
1. Which keyword handles every remaining case in a chain of conditions?
2. How does Python know which lines belong to an if block?
Self-graded — answer then check below.