Conditional expressions
An if statement chooses which code runs. Often, though, the only thing that changes is a value:
temperature = 25
if temperature > 20:
print("warm")
else:
print("cold")
warmA conditional expression chooses between two values in one line. It reads almost like English: "warm" if temperature > 20 else "cold" is "warm" when the condition is true, and "cold" otherwise. Since it's an expression, it goes anywhere a value can go:
temperature = 25
print("warm" if temperature > 20 else "cold")
label = "even" if temperature % 2 == 0 else "odd"
print(label)
warm
oddThe order is: the value for true, then if and the condition, then else and the value for false. (Some languages call this the ternary operator, because it has three parts.)
Where it shines
Small choices inside a longer line, such as a word that changes with a number, are where a conditional expression saves the most. Without it, each line would need an if statement of four lines:
for count in [0, 1, 5]:
print(f"{count} {'file' if count == 1 else 'files'} found")
0 files found
1 file found
5 files foundIt works in a return too:
def larger(a, b):
return a if a > b else b
print(larger(3, 8))
print(larger(10, -2))
8
10The else is not optional
An expression must always have a value, so the else part is required. Without it, Python can't read the line:
score = 7
print("passed" if score >= 5)
File "main.py", line 2
print("passed" if score >= 5)
^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: expected 'else' after 'if' expressionUse a conditional expression to choose a value. When the two cases do different things, or there are more than two cases, an ordinary if, elif and else is easier to read.