if / elif / else Statements
Conditional statements let your program make decisions. The if/elif/else structure evaluates conditions and executes different code blocks based on whether conditions are True or False.
Conditional Statements
Python uses if/elif/else to make decisions. The condition must evaluate to True or False. Use comparison operators (==, !=, >, <, >=, <=) and logical operators (and, or, not) to build conditions. Indentation defines the code block.
Everything in Python is an object — use type() to check
if/elif/else Code
age = 20
# Simple if
if age >= 18:
print("You are an adult")
# if-else
temperature = 35
if temperature > 30:
print("It's hot!")
else:
print("It's cool.")
# if-elif-else
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Score: {score}, Grade: {grade}")
# Multiple conditions
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive!")
elif age >= 18:
print("Get a license first.")
else:
print("Too young to drive.")Try It Yourself: Grade Calculator
Tip
Tip
Keep conditions simple. Instead of nested not/and/or, use named variables: is_valid = x > 5 and y < 10 then if not is_valid:.
Common Mistake
Warning
Using = instead of == in conditions. if x = 5: is a SyntaxError. Use == for comparison. Also if x == True: is redundant — just write if x:.
Practice Task
Note
Build a ticket pricing system: (1) Under 5: free. (2) 5-12: $10. (3) 13-59: $25. (4) 60+: $15. (5) Add a VIP boolean that doubles the price.