If, Elif, and Else
20 min In ProgressLearning Objectives
- Write conditional blocks with if
- Chain conditions with elif
- Provide fallback actions with else
The if Statement
An if statement runs a block of code only when its condition is True. Indentation matters in Python.
temperature = 85
if temperature > 80:
print("It is hot outside!")
print("Stay hydrated.")
if / elif / else
Use elif to check additional conditions, and else as a catch-all.
score = 78
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("D or F")
Course Example: True or False Quiz
A simple quiz that checks user input and responds accordingly.
answer = input("Return TRUE or FALSE: Python was released in 1991:\n")
if answer == "TRUE":
print('Correct')
elif answer == "FALSE":
print('Wrong')
elif answer != ("TRUE" or "FALSE"):
print('Please answer TRUE or FALSE')
print('Bye!')
📝 Exercise: Number Classifier
Write a script that takes a number and prints whether it is positive, negative, or zero.
code.py
Output