if, elif, and else
Now that you can produce booleans, you can make your program decide. An if statement runs a block of code only when a condition is true. Add elif and else and your program can choose between many paths.
What You'll Learn
- The
ifstatement and Python's indentation - Adding
elifandelsebranches - Putting conditions in the right order
- The one-line ternary expression
The if Statement
Two things to notice: the line ends with a colon :, and the code inside is indented with 4 spaces. Python uses that indentation (not braces) to know what belongs inside the if.
if / else
else runs when the condition is false:
if / elif / else
Use elif (short for "else if") to test more conditions in order. Only the first true branch runs:
Order Matters
Because only the first true branch runs, put the most specific conditions first. This diagram shows how a value flows through the checks:
Decision
How big is x?
- If x > 20
Greater than 20
- If else if x > 10
Greater than 10
- If else
10 or less
If you checked x > 10 first, a value like 25 would stop there and never reach x > 20.
The Ternary Expression
For a simple either/or choice, you can pick a value in one line:
Key Takeaways
if condition:runs indented code when the condition is true- Python uses 4-space indentation to mark blocks
elifadds more conditions;elseis the fallback- Only the first true branch runs, so order matters
- Ternary:
value_if_true if condition else value_if_false

