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:
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:
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:
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 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:
If score is anything other than 100, nothing prints. That's fine.
Key takeaways
ifruns a block of code when a condition isTrueelseruns…
No comments yet. Add the first comment to start the discussion.