Python decides between paths with if, elif and else. The block that runs is chosen by the first condition that turns out to be true.
marks = 74
if marks >= 80:
print("Distinction")
elif marks >= 50:
print("Pass")
else:
print("Try again")The syntax rules#
Two things Python insists on:
- A colon at the end of the
if,elifandelselines - Consistent indentation for the block underneath — four spaces is the convention
if logged_in:
print("Welcome back") # inside the if
print("Loading...") # also inside
print("Done") # outside — always runsMiss the colon and you get SyntaxError: expected ':'. Get the indentation wrong and you get IndentationError. Both messages point at the exact line.
Comparison operators#
a, b = 5, 10
print(a == b) # False — equal to
print(a != b) # True — not equal to
print(a < b) # True
print(a >= 5) # True
print(1 < a < 10) # True — Python allows chainingThat last line is a genuine Python convenience. Most languages need a > 1 and a < 10.
and, or, not#
age = 22
has_id = True
if age >= 18 and has_id:
print("Allowed")
if age < 13 or age > 65:
print("Discounted ticket")
if not has_id:
print("Bring identification")Python short-circuits: in a and b, if a is false it never evaluates b. This is useful for guarding:
if user is not None and user["active"]:
print("Active user")Truthiness#
You do not always need a comparison. These are all false: False, None, 0, 0.0, "", [], {}, (). Everything else is true.
name = input("Name: ")
if name:
print(f"Hello {name}")
else:
print("You did not type anything")Order matters in an elif chain#
score = 95
# Wrong — everything above 50 stops here
if score >= 50:
grade = "Pass"
elif score >= 90:
grade = "Distinction" # unreachable
# Right — narrowest condition first
if score >= 90:
grade = "Distinction"
elif score >= 50:
grade = "Pass"Only one branch ever runs. Once a condition matches, Python skips the rest of the chain.
Membership checks#
allowed = ["admin", "editor"]
role = "editor"
if role in allowed:
print("Access granted")
if "@" not in email:
print("That does not look like an email address")The one-line form#
status = "adult" if age >= 18 else "minor"Fine for a simple two-way choice. Do not chain several together — a normal if block is easier to read.
match statements#
Python 3.10 and later have match for comparing one value against several options:
command = "start"
match command:
case "start":
print("Starting")
case "stop":
print("Stopping")
case _:
print("Unknown command")Useful, but an if / elif chain does the same job and works everywhere.
Questions people ask#
Why does my if block run when I did not expect it to?
Check for = where you meant ==, and check the type of the value being compared. Those two account for most surprises.
Can I have an if with no else?
Yes. else is optional. If the condition is false and there is no else, nothing happens and the program moves on.
How do I check several values at once?
Use in with a list or tuple: if role in ("admin", "editor", "owner"):. Much cleaner than three or comparisons.