Making Decisions: if / elif / else
Teach your Python program to choose different paths
Big Idea: Real programs need to make decisions. "If it is raining, take an umbrella. Otherwise, wear sunglasses." In Python we make decisions with
if, elif, and else. The program checks a condition (something that is either True or False) and runs different code depending on the answer.
By the end you will be able to:
- compare values with
==,!=,<,>,<=,>=, - run code only when a condition is True using
if, - give a backup path with
elseand extra paths withelif, - combine conditions with
and,or, andnot.
1. Comparing values: True or False
A comparison asks a yes/no question about two values. Python answers with a boolean value: either True or False (note the capital letters).
| Operator | Means | Example | Result |
|---|---|---|---|
== | is equal to | 5 == 5 | True |
!= | is not equal to | 5 != 3 | True |
> | is greater than | 5 > 8 | False |
< | is less than | 5 < 8 | True |
>= | greater than or equal | 5 >= 5 | True |
<= | less than or equal | 9 <= 5 | False |
Let's try it in real code:
age = 20
print(age >= 18)
print(age == 18)
print(age != 18)
Output:
True
False
True
Watch out: one
= assigns a value (age = 20). Two == compares (age == 20). They are not the same! 2. The if statement
An if statement runs a block of code only when its condition is True. Two things are very important:
- The
ifline ends with a colon: - The code to run is indented (moved to the right, usually 4 spaces). The indented lines are "inside" the if.
age = 20
if age >= 18:
print("You can vote!")
print("Program finished")
Output:
You can vote!
Program finished
Because age >= 18 is True, the indented line runs. The last line is not indented, so it always runs. If age were 10, the first message would be skipped and only "Program finished" would appear.