Level 1
0 / 100 XP

Making decisions with if, elif, and else

Booleans tell you what's true. But knowing something is true isn't useful unless your program can act on it. That's what if, elif, and else are for.

The if statement

An if statement runs a block of code only when a condition is True:

Python
temperature = 35 if temperature > 30: print("It's hot outside")

The code inside the if block only runs if temperature > 30 is True. If it's False, Python skips it entirely.

Indentation matters

Python uses indentation to know what belongs inside the if block. The standard is 4 spaces:

Python
temperature = 35 if temperature > 30: print("It's hot outside") # inside the if block print("Wear sunscreen") # also inside the if block print("Have a good day") # outside — always runs

Get the indentation wrong and Python will either throw an error or run code you didn't intend.

else — the fallback

else runs when the if condition is False:

Python
temperature = 15 if temperature > 30: print("It's hot outside") else: print("It's not that hot")

Exactly one of these will always run. If the condition is True, the if block runs. If it's False, the else block runs.

elif — additional conditions

elif lets you check more conditions before falling back to else:

Python
temperature = 20 if temperature > 30: print("Hot") elif temperature > 20: print("Warm") elif temperature > 10: print("Cool") else: print("Cold")

Python checks each condition in order and runs the first one that's True. Once a match is found, the rest are skipped entirely.

You don't always need else

else is optional. Sometimes you only want to act when something specific is true and do nothing otherwise:

Python
score = 100 if score == 100: print("Perfect score!")

If score is anything other than 100, nothing prints. That's fine.

Key takeaways

  • if runs a block of code when a condition is True
  • else runs…