Sub topic 13
One-line conditional expressions
This chapter assumes you can write if/else statements, use comparison operators, and define simple functions. A conditional expression is the one-line form of a two-way choice. It produces a value, so you can use it anywhere Python expects an expression.
The syntax
The form is value_if_true if condition else value_if_false. The condition is evaluated first. Python then evaluates only the chosen branch.
n = 4
label = 'even' if n % 2 == 0 else 'odd'
print(label)This prints even. It is equivalent to the following statement version.
n = 4
if n % 2 == 0:
label = 'even'
else:
label = 'odd'
print(label)The difference is that the first form is an expression. A statement such as if cannot appear inside a function call, a return value, or an f-string. A conditional expression can.
def parity(n):
return 'even' if n % 2 == 0 else 'odd'
for number in (1, 2, 3):
print(f"{number} is {parity(number)}")Only the chosen branch runs
The branch that is not selected is never evaluated. This lets you guard an operation that would fail.
items = []
first = items[0] if items else None
print(first)Because an empty list is falsy, items[0] is skipped and no IndexError is raised. The result is None.
Chaining and precedence
You can chain conditional expressions, and the else part can hold another one. This reads like an elif chain.
score = 83
grade = 'A' if score >= 90 else 'B' if score >= 80 else 'C'
print(grade)This prints B. Each extra level makes the line harder to read, so switch to an elif chain after two choices.
The conditional expression has very low precedence. Only lambda and the assignment forms bind more loosely. If you combine it with other operators, add parentheses.
n = 5
text = 'n is ' + ('big' if n > 3 else 'small')
print(text)Without the parentheses, Python reads 'n is ' + 'big' as the true value, and the result is wrong. In this example it would print n is big for a large n but an empty-looking small never gets the prefix.
When to prefer each form
| Situation | Better choice |
|---|---|
| Pick one of two simple values | Conditional expression |
| Choose a default for a missing value | Conditional expression |
| Run several statements per branch | `if`/`else` statement |
| Three or more cases | `elif` chain or `match` |
| Branches have side effects such as printing | `if`/`else` statement |
Common mistakes
Using a conditional expression only for its side effects is a common error. This works, but it hides the intent.
ready = True
print('go') if ready else print('wait')An if/else statement states this more clearly.
Another mistake is using or as a default when 0 or an empty string is a valid value.
count = 0
shown = count or 'none'
print(shown)
shown = count if count is not None else 'none'
print(shown)The first form prints none because 0 is falsy. The second prints 0, because it tests for None directly.
Exercise
What does result = 'yes' if [] else 'no' assign to result, and why?
Show answer
It assigns 'no'. An empty list is falsy, so the condition is False and Python evaluates the value after else.
Exercise
Rewrite this as a single conditional expression: if temp is above 30, set advice to 'hot'. Otherwise set it to 'fine'.
Show answer
advice = 'hot' if temp > 30 else 'fine'