Conditions
In short
if runs a block of code only when a condition is True; elif checks another condition and else catches everything left. Conditions use comparisons such as ==, < and in, combined with and, or and not. Python uses indentation, not brackets, to mark each block.
if, elif and else
temperature = 18
if temperature > 25:
print("Hot — shorts weather")
elif temperature > 15:
print("Mild — bring a light jacket")
else:
print("Cold — wear a coat")Output
Mild — bring a light jacket
- End each condition line with a colon
:. - Indent the block underneath by 4 spaces. The indentation is the block.
- Python checks from the top and runs only the first branch that's true.
Comparison operators
| Operator | Meaning | Example |
|---|---|---|
== | equal | age == 18 |
!= | not equal | status != "done" |
< <= | less (or equal) | price < 10 |
> >= | greater (or equal) | score >= 50 |
in | is inside | "@" in email |
is | is the same object (use for None) | result is None |
Combining conditions
age = 34
has_ticket = True
if age >= 18 and has_ticket:
print("Welcome in")
if not has_ticket or age < 18:
print("Sorry")
else:
print("Enjoy the show")
print(18 <= age < 65) # chained comparisonOutput
Welcome in Enjoy the show True
Truthy and falsy values
for value in [0, 7, "", "hi", [], [1], None]:
print(repr(value), bool(value))Output
0 False 7 True '' False 'hi' True [] False [1] True None False
Empty things and zero count as false, so you can write if items: instead of if len(items) > 0:.
One-line conditional expression
stock = 0
label = "in stock" if stock > 0 else "sold out"
print(label)Output
sold out
match-case: choosing between many patterns
def describe(command: str) -> str:
match command.split():
case ["go", direction]:
return f"Walking {direction}"
case ["pick", "up", item]:
return f"You take the {item}"
case ["quit" | "exit"]:
return "Bye!"
case _:
return "I don't understand"
print(describe("go north"))
print(describe("pick up lamp"))
print(describe("exit"))
print(describe("dance"))Output
Walking north You take the lamp Bye! I don't understand
match (Python 3.10+) compares a value against shapes, not just single values, and can pull parts out into names. case _ catches everything else. For simple yes/no choices, if is still clearer.
Practice
Write grades for these scores: scores = [92, 75, 58, 81]. Print one line per score: A for 90 and above, B for 75–89, C for 60–74 and F below 60, formatted like 92: A.
Expected output:
92: A 75: B 58: F 81: B