Module 5 · Python for Beginners
"Conditions: if, elif and else"
Make your code decide. Comparison and logical operators, if, elif and else, indentation, nested decisions, the one-line form, and which values count as true.
About 30 minutes
Open in ColabEvery example as a notebook you can run, edit and save to your Google Drive.
Comparisons give True or False
Every decision starts with a question that's either true or false. Comparison operators ask those questions:
| Operator | Asks | Example | Result |
|---|---|---|---|
== | equal to? | 5 == 5 | True |
!= | not equal to? | 5 != 3 | True |
> | greater than? | 5 > 3 | True |
< | less than? | 5 < 3 | False |
>= | greater than or equal? | 5 >= 5 | True |
<= | less than or equal? | 4 <= 3 | False |
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
True
False
FalseText comparisons are exact: capitals matter, so "Lagos" and "lagos" aren't equal.
if: do something only when it's true
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Low balance: top up soon
DoneThe parts of an if:
if, then a condition, then a colon:.- The lines that belong to it are indented by four spaces. That's the block.
- When the condition is true, the block runs. When it's false, Python skips it.
- The first line back at the left edge (
print("Done")) isn't part of theif: it always runs.
Indentation is part of the code
In most languages, indentation is just for looks. In Python, it decides which lines belong to the if:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Balance checkedBoth indented lines were skipped because the condition was false. Colab indents for you when you press Enter after a colon. Use four spaces, and keep it consistent.
else: the alternative
else runs when the condition is false. Exactly one of the two blocks runs:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Fail: register for the resitelif: several choices
elif ("else if") adds more conditions. Python checks them from the top and runs the first block whose condition is true, then skips the rest:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Score 67 is grade B67 isn't >= 70, so Python moves on; it is >= 60, so grade is "B" and the remaining checks are skipped. That's why the order matters: put the highest band first. If score >= 50 came first, 67 would be graded C.
Combining conditions: and, or, not
| Operator | True when | Example |
|---|---|---|
and | both sides are true | age >= 18 and has_id |
or | at least one side is true | day == "Sat" or day == "Sun" |
not | the condition is false | not is_paid |
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Eligible for the scholarshipEdit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
WeekendNote that each side of or is a complete comparison. day == "Saturday" or "Sunday" looks right but is always true, a classic bug; the in operator below is a neater way to write it.
Ranges in one go
Python lets you chain comparisons the way you'd write them in maths:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Normal for LagosChecking membership with in
in checks whether a value is in a list (or a string):
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
WeekendNested decisions
A block can contain another if. Indent once more for each level:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Fee: ₦20,000More than two or three levels deep gets hard to read. Often and or elif does the same job more simply.
The one-line form
For a simple either-or value, there's a short form: value_if_true if condition else value_if_false:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
PassUse it only when it's easy to read. For anything longer, write a full if/else.
Truthy and falsy values
if doesn't need a comparison. Any value can be tested, and Python treats some as false:
| Treated as false | Everything else is true |
|---|---|
False, None, 0, 0.0, "" (empty text), [] (empty list) | True, any non-zero number, any non-empty text or list |
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Please enter your nameThat's a common way to check that someone actually typed something.
When it goes wrong
if score >= 50
print("Pass")Output
SyntaxError: expected ':'Missing colon. Every if, elif and else line ends with :.
if score >= 50:
print("Pass")Output
IndentationError: expected an indented block after 'if' statement on line 1Missing indentation. The block must be indented.
if score = 70:
print("Exactly 70")Output
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?= instead of ==. Python even suggests the fix.
Summary
| You want to... | Write |
|---|---|
| run code only if true | if cond: + indented block |
| choose between two | if cond: ... else: ... |
| choose between several | if ... elif ... elif ... else ... (highest band first) |
| require both | a and b |
| accept either | a or b (full comparisons on both sides) |
| reverse a condition | not a |
| check a range | low <= x <= high |
| check a list | x in [...] |
| pick a value in one line | a if cond else b |
Try it
Practice
Using the grading rules in the lesson (70+ A, 60+ B, 50+ C, 45+ D, otherwise F), what grade does a score of 46 get?
Practice
cgpa = 3.9 and attendance = 90. Is cgpa >= 4.0 and attendance >= 75 True or False?
Practice
What does "Pass" if 49 >= 50 else "Fail" give? Type it without quotes.
Task
8 minWrite a data plan advisor: store how many GB someone used last month in a variable, then use if, elif and else to recommend a plan (for example under 2 GB: Basic; 2 to 10 GB: Standard; over 10 GB: Premium), and print the recommendation with an f-string. Add one extra condition using and or or (for example, students get a discount). Paste your code.
Your work is checked for
- if, elif and else, each ending with a colon
- Blocks are indented
- Uses comparisons like < or >=
- Uses and or or
- Prints with an f-string
- Compares with == or >= / <=, not a single =
Earn your badge
Take the module check
Questions on this module. Pass and you earn the Python Decisions badge, free.
Create a free account to earn the badge