The conditional expression
Picture the sign on a shop door. It always shows one of two words: "Open" or "Closed". The clock decides which word to show: one in the daytime, the other at night. The sign itself does nothing, it only shows one of two values.
A program often needs the same kind of sign: an if is needed only to choose one of two values. A statement with two branches spends four lines on such a choice and repeats the variable name twice:
n = -7
if n >= 0:
sign = "plus"
else:
sign = "minus"
print(sign) # minus
sign = "plus" if n >= 0 else "minus"
print(sign) # minusLet's compare the two forms:
- The
ifstatement with anelsebranch puts one of two words intosign. - The line
sign = "plus" if n >= 0 else "minus"does the same in one line. - Both print
minus, because-7is less than zero.
The form a if condition else b is called a conditional expression. If the condition is true, its value is a, otherwise b.
How the form reads
A conditional expression reads almost like a phrase: ""plus" if n >= 0, else "minus"". It has three parts:
a— the value when the condition is true;if condition— the check;else b— the value when the condition is false.
Python evaluates the condition first and then only one of the two values. The other value is not evaluated at all.
Interviewers sometimes ask whether Python has a ternary operator, that is, a choice of a value made of three parts. It does: it is the conditional expression a if condition else b.
An expression, not a statement
A conditional expression gives a value, so it goes where a value is expected:
- after
=; - as an argument of
print; - after
return.
Its else part cannot be left out: without it the expression has nothing to return when the condition is false. It cannot run several statements. It only chooses a value, and everything else stays with the if statement.
This is where the sign analogy stops working. The two words on a sign are written once and for all. In a conditional expression any expression may stand in place of a and b, for example n * 2. Python evaluates it anew each time the line runs.
A chain in one line
Another conditional expression may follow else. Such a chain reads from left to right, like an if with one elif branch:
def describe(n):
return "plus" if n > 0 else "minus" if n < 0 else "zero"
print(describe(5)) # plus
print(describe(-2)) # minus
print(describe(0)) # zeroLet's go through the three calls:
- First
n > 0is checked. For5it is true, and the result is"plus". - For
-2it is false, and the whole right part"minus" if n < 0 else "zero"is evaluated. Theren < 0is true, and the result is"minus". - For
0both conditions are false, and the result is"zero".
One such link is enough. With three conditions or more, an if statement with elif branches is clearer.
abs, min and max
Some choices come up so often that there are built-in functions for them:
print(abs(-7), abs(7)) # 7 7
print(max(3, 8), min(3, 8, 1)) # 8 1
print(max(3, 2.0), min(2.5, 3)) # 3 2.5abs
abs(x) returns the absolute value of a number—its value without the minus sign. It replaces the expression x if x >= 0 else -x.
max and min
max returns the largest of its arguments and min the smallest. There may be more than two arguments: min(3, 8, 1) gives 1.
Both functions return one of their arguments as it is, with no type conversion: max(3, 2.0) gives the integer 3, not 3.0. The form max(a, b) gives the same as the expression a if a >= b else b, only shorter.
Common mistake
The else part of a conditional expression is missing:
n = -7
sign = "plus" if n >= 0 # ✗SyntaxError: expected 'else' after 'if' expressionWithout else the expression does not know which value to give when the condition is false, so the file does not run. If nothing needs to happen when the condition is false, write an if statement without else.
Key points
a if condition else bgivesawhen the condition is true andbwhen it is false, and only one of them is evaluated.- It is an expression: it goes after
=, into an argument or afterreturn, and itselsepart is required. - With three conditions or more, an
ifstatement withelifbranches is clearer. maxandminreturn one of their arguments with no type conversion, andabsreturns the number without its minus sign.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.