Sub topic 11
Conditional expressions
This chapter assumes you know Python's comparison operators, truthiness, and the short-circuit behavior of and and or. A conditional expression chooses between two values inside a single expression. It is Python's version of the ternary operator found in other languages.
Syntax and evaluation order
The form is value_if_true if condition else value_if_false. The condition is written in the middle, which surprises people used to condition ? a : b.
n = 7
label = "even" if n % 2 == 0 else "odd"
print(label)This prints odd. Python evaluates in this order:
- It evaluates the condition and tests its truthiness.
- It evaluates only the chosen branch.
- It returns that branch's value as the result of the whole expression.
The unchosen branch never runs. This is what makes guard patterns safe.
def risky():
print("risky called")
return 1
a, b = 10, 0
ratio = a / b if b != 0 else None
print(ratio)
value = risky() if False else 0
print(value)The output is None, then 0. The division never happens, and risky is never called, so risky called is never printed.
placeholderThe diagram below shows the flow.
It is an expression, not a statement
An if statement runs code. A conditional expression produces a value, so it can appear anywhere a value can: in an assignment, a function argument, a return, an f-string, or a lambda body.
def describe(count):
return f"{count} item{'s' if count != 1 else ''}"
sign = lambda n: "negative" if n < 0 else "non-negative"
print(describe(1))
print(describe(3))
print(sign(-4))This prints 1 item, 3 items, and negative. A statement-style if cannot go inside a lambda or an f-string, which is why the expression form is useful there.
The else part is required. An expression must always produce a value, so "even" if n % 2 == 0 alone is a SyntaxError.
Precedence
A conditional expression has very low precedence. Only lambda and the walrus operator := bind more loosely. Everything on either side of if and else is grouped first.
x = 1 + 2 if False else 3 + 4
print(x)This prints 7. Python reads it as (1 + 2) if False else (3 + 4). You do not need parentheses around the branches here, but you do in two situations:
- You want to use the result inside a larger expression, such as
10 + (1 if flag else 2). Without the parentheses, the10 +becomes part of the true branch. - You use a comma. In
t = 1 if True else 2, 3, the comma is lower than the conditional expression, sotis the tuple(1, 3). Write1 if True else (2, 3)if you meant one of two tuples.
Chaining and nesting
The conditional expression is right-associative, so you can chain else if style tests without parentheses.
def grade(score):
return "A" if score >= 90 else "B" if score >= 80 else "C"
print(grade(95))
print(grade(85))
print(grade(40))This prints A, B, C. Python reads the return line as "A" if score >= 90 else ("B" if score >= 80 else "C").
Chains work, but they get hard to read after two levels. If you need three or more branches, or if branches contain long expressions, use an if/elif statement or a dictionary lookup. Put another way, use a conditional expression when the result is a small, simple choice.
Conditional expressions in comprehensions
A comprehension has two different places where if can appear, and they do different jobs.
nums = [1, 2, 3, 4, 5]
labels = ["even" if k % 2 == 0 else "odd" for k in nums]
evens = [k for k in nums if k % 2 == 0]
print(labels)
print(evens)The first line transforms every element. The if/else comes before the for, so it is a conditional expression, and else is required. The second line filters elements. The if comes after the for and takes no else. The output is:
['odd', 'even', 'odd', 'even', 'odd']
[2, 4]Mixing these up gives a SyntaxError (else after a filter) or the wrong list length.
Relationship to `and` / `or`
Before conditional expressions existed, people wrote condition and a or b. This idiom has a bug: if a is falsy, the expression falls through to b even when the condition is true.
flag = True
old_style = flag and "" or "fallback"
new_style = "" if flag else "fallback"
print(repr(old_style))
print(repr(new_style))The output is 'fallback' and then ''. The conditional expression is correct because it tests only the condition. Never use and ... or ... as a ternary.
`or` for defaults versus an explicit test
The expression name or "anonymous" is shorter, but it replaces every falsy value: "", 0, [], and None. If only None should trigger the default, say so.
name = ""
by_truthiness = name or "anonymous"
by_none_check = name if name is not None else "anonymous"
print(repr(by_truthiness))
print(repr(by_none_check))The output is 'anonymous' and then ''. Choose the form that matches your intent. This matters most for numbers, where 0 is often a valid value: timeout or 30 silently turns a timeout of 0 into 30.
Common mistakes
| Mistake | Why it fails | Fix |
|---|---|---|
| Omitting `else` | The expression has no value for the false case | Add `else`, or use an `if` statement |
| Writing `cond ? a : b` | That is not Python syntax | Write `a if cond else b` |
| `10 + 1 if flag else 2` | The `10 +` joins the true branch only | Write `10 + (1 if flag else 2)` |
| Using it for side effects, such as `print("a") if x else print("b")` | It works, but it hides statements inside an expression | Use an `if` statement |
| Deep nesting | Hard to read and easy to mis-group | Use `if`/`elif`, or a dictionary |
Summary of the rules
- The form is
a if condition else b, andelseis mandatory. - Only the chosen branch is evaluated, so guards such as
x / y if y else 0are safe. - Precedence is very low, so add parentheses when you embed it in a larger expression.
- It is right-associative, so chains group from the right.
- Do not replace it with
condition and a or b.
Exercise
What do these two lines print, and why? Line 1: print("x" if 0 else "y" if "" else "z"). Line 2: print(10 + 1 if False else 2).
Show answer
Line 1 prints z. It groups as "x" if 0 else ("y" if "" else "z"). The first condition 0 is falsy, so Python evaluates the second conditional expression, whose condition "" is also falsy, so the result is "z". Line 2 prints 2. It groups as (10 + 1) if False else 2, and since the condition is false, the false branch 2 is returned. To add 10 to the chosen value, write 10 + (1 if False else 2), which gives 12.
Exercise
Rewrite port = config_port or 8080 so that a config_port of 0 is kept, and only None falls back to 8080.
Show answer
port = config_port if config_port is not None else 8080. The or version treats 0 as falsy and replaces it, while the explicit is not None test replaces only None.