So far every line has run, top to bottom. Real programs choose: a discount only for members, an error only when input is wrong. That is what if is for.
if#
temperature = 31
if temperature > 30:
print("It's hot")
print("Drink water")
print("Done")
The condition ends with a colon, and the lines that belong to it are indented. Both lines under if run only when the condition is true; Done runs either way, because it is back at the left edge.
else#
if temperature > 30:
print("It's hot")
else:
print("It's fine")
Exactly one of the two branches runs.
elif#
For more than two choices, chain with elif (short for "else if"):
marks = 72
if marks >= 90:
grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 60:
grade = "C"
else:
grade = "F"
print(grade) # C
Python checks each condition in order and runs the first one that is true, then skips the rest. That is why the order matters: put >= 60 first and every passing mark becomes a C.
Combining conditions#
age = 25
has_id = True
if age >= 18 and has_id:
print("Allowed in")
if day == "Saturday" or day == "Sunday":
print("Weekend")
if not has_id:
print("Bring ID")
Membership with in reads well for several values:
if day in ("Saturday", "Sunday"):
print("Weekend")
What counts as true#
Any value can be used as a condition. These count as false: False, None, 0, 0.0, "" (empty string), [] (empty list), {} (empty dict). Everything else is true.
name = input("Name: ")
if name:
print(f"Hi {name}")
else:
print("You didn't type anything")
if name: reads "if there is a name". It is the usual Python way to check for empty text or an empty list.
Nested decisions#
An if can sit inside another, indented one more level:
if logged_in:
if is_admin:
print("Admin panel")
else:
print("Dashboard")
else:
print("Please sign in")
Deep nesting gets hard to read. Often you can flatten it by handling the special case first:
if not logged_in:
print("Please sign in")
elif is_admin:
print("Admin panel")
else:
print("Dashboard")
The conditional expression#
For choosing between two values, there is a one-line form:
label = "even" if n % 2 == 0 else "odd"
Read it as "even if n is divisible by two, else odd". Use it for short choices of a value; use a full if when there is more to do.
Common mistakes#
- Forgetting the colon at the end of
if,eliforelse. - Indenting one line of a block differently from the others.
if x = 5:instead ofif x == 5:. Python refuses the first, which is helpful.- Ordering
elifchecks so an earlier, wider one swallows a later, narrower one.
Key points#
if,elifandelsechoose which block runs; only the first true branch does.- Blocks are marked by a colon and indentation.
- Empty values and zero count as false.
a if condition else bpicks between two values in one line.
Next: doing things more than once, with loops.