if, elif and else
An if statement runs a block of code only when a condition is true.
Python
temperature = 34
if temperature > 30:
print("It's a hot day.")
print("Stay hydrated!")
print("Have a good day.")Notice the colon and the indented block. Change the temperature to 20 and run it again.
else
else gives the code to run when the condition is false:
Python
age = int(input("Age: "))
if age >= 18:
print("You can vote.")
else:
print(f"You can vote in {18 - age} year(s).")elif
elif ("else if") checks further conditions. Python tests them top to bottom and runs only the first block whose condition is true:
Python
score = 72
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print("Grade:", grade)Order matters. If the score >= 60 test came first, a score of 95 would get a "D".
Nested conditions
An if can sit inside another if:
Python
has_account = True
password_ok = False
if has_account:
if password_ok:
print("Welcome back!")
else:
print("Wrong password.")
else:
print("Please sign up.")Deep nesting gets hard to read; often and or an early elif makes it flatter.
Conditional expressions
For simple choices there is a one-line form: value_if_true if condition else value_if_false.
Python
n = 7
kind = "even" if n % 2 == 0 else "odd"
print(n, "is", kind)
items = 1
print(f"{items} item{'s' if items != 1 else ''}")An empty block
A block cannot be empty. Use pass as a placeholder while you are still writing:
Python
logged_in = False
if logged_in:
pass # TODO: show the dashboard
else:
print("Please sign in")Finished this lesson?Mark it complete to earn +20 XP and move your progress on.