Sub topic 11
Conditional expressions
This chapter assumes you know comparison operators, truthiness, and short-circuit evaluation from the earlier chapters.
The syntax
A conditional expression chooses between two values. Its form is value_if_true if condition else value_if_false. It is an expression, so it produces a value. You can use it anywhere a value fits: in an assignment, a function argument, a return, or an f-string.
n = 7
label = "even" if n % 2 == 0 else "odd"
print(label)Python evaluates the condition first. It then evaluates only the chosen branch. The other branch never runs.
def safe_ratio(a, b):
return a / b if b != 0 else None
print(safe_ratio(6, 3))
print(safe_ratio(1, 0))The second call prints None. The expression a / b is never evaluated, so there is no ZeroDivisionError.
Expression versus statement
An if statement runs code for its effects. A conditional expression computes a value. Use the expression when you are choosing between two values. Use the statement when each branch performs actions, such as several assignments or calls.
Why not `and` / `or`?
Before this syntax existed, people wrote condition and a or b. That idiom fails when a is falsy, because and returns a, and then or moves on to b.
flag = True
print(flag and "" or "fallback")
print("" if flag else "fallback")The first line prints fallback, even though flag is true. The second line prints an empty string, which is the correct result.
Precedence and chaining
A conditional expression has very low precedence, just above lambda and the walrus operator. In 10 + 5 if False else 1, the + is grouped first.
print(10 + 5 if False else 1)This prints 1, because the condition is false. Add parentheses when you embed a conditional inside a larger expression.
The operator is right-associative, so you can chain it:
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C"
print(grade)Python reads this as "A" if score >= 90 else ("B" if score >= 80 else "C"). The output is B.
Common errors
- Writing the condition first, as in
if x else a. The value for the true case always comes first. - Leaving out
else. Theelsepart is required, because an expression must always produce a value. - Using it only for side effects, such as
print("a") if x else print("b"). It works, but anifstatement is clearer.
Exercise
What does "yes" if [] else "no" evaluate to, and why?
Show answer
It evaluates to "no". An empty list is falsy, so Python takes the branch after else and never evaluates "yes".
Exercise
Rewrite result = x > 0 and "positive" or "non-positive" as a conditional expression. Does the original have the and/or problem?
Show answer
result = "positive" if x > 0 else "non-positive". The original works here because "positive" is a non-empty string and so is truthy. The problem would appear if the middle value could be falsy.