Sub topic 1
Python if, elif, and else Statements
Prerequisites
This chapter assumes you can run Python code and use variables, basic data types, print(), and simple functions.
Conditions: comparison operators and boolean expressions
A condition is an expression that produces True or False. Comparison operators build conditions from values:
| Operator | Meaning | Example |
|---|---|---|
| `==` | equal to | `age == 18` |
| `!=` | not equal to | `status != "closed"` |
| `>` or `<` | greater or less than | `score > 50` |
| `>=` or `<=` | greater or equal, less or equal | `age >= 18` |
A boolean expression can combine conditions with and, or, and not.
age = 20
has_ticket = True
can_enter = age >= 18 and has_ticket
print(can_enter) # Trueand requires both parts to be true. or requires at least one part to be true. not reverses a boolean value.
Colons and indentation: how Python marks a block
A block is a group of statements controlled by a compound statement. Python starts a block with a colon (:), then uses consistent indentation to show which statements belong to it. Four spaces is the usual indentation.
flowchart TD
A[Evaluate condition] -->|True| B[Run indented block]
A -->|False| C[Skip block]The if statement
An if statement runs its block only when its condition is true.
temperature = 22
if temperature > 20:
print("Light jacket weather")Python evaluates temperature > 20 first. Because the result is True, it runs the indented print() statement. If the result is False, Python skips that block and continues after it.
Handling the other case with else
Use else for the alternative path. An else clause must follow an if block and also ends with a colon.
age = 16
if age >= 18:
message = "adult"
else:
message = "minor"
print(message)Exactly one branch runs here. The condition is false, so Python skips the first block and runs the else block.
Remember that = assigns a value, while == compares values. A condition such as age = 18 is invalid in an if statement because assignment is not a comparison.
Exercise
What does this code print? n = 3; if n == 3: print("yes") else: print("no")
Show answer
It prints yes, because n == 3 evaluates to True.