Lesson 5 of 21 · 2 min
if-else — Two Options: One Always Runs
The WHY — Why if-else?
if alone only runs code when the condition is True and does nothing when it is False. if-else gives you two paths: one for True, one for False. Exactly one of the two blocks always runs.
age = 17 # a person's age
if age >= 18: # check: is age 18 or more?
print("You can vote.") # runs ONLY if age >= 18 is True
else: # else runs when the if condition is False
print("Too young to vote.") # runs ONLY if age >= 18 is False
Output: Too young to vote.
A Practical Example
temperature = 35 # temperature in Celsius
if temperature > 30: # check: is it hotter than 30?
print("It's hot! Drink water.") # runs if temperature > 30
else:
print("The weather is comfortable.") # runs if temperature is 30 or below
Output: It's hot! Drink water.
