In one of the previous articles we were talking about conditional statements. Today we’ll be talking about the ternary if statement.
Here’s the video version of this article:
We can simplify short conditional statements and the blocks that follow by using the so-called ternary if statement. Here’s a simple regular piece of conditional code:
>>> a, b = 7, 3
>>> if(a > b):
... winner = a
... else:
... winner = b
...
We can now rewrite the code using the ternary if statement:
winner = a if (a > b) else b
The general syntax is:
x = a if(condition) else b
So, a is assigned to x provided the condition is met. Otherwise, b is assigned to x.
Ternary if Statement in Expressions
The ternary if statement can be also used in expressions, like for example:
>>> a, b = 5, 8
>>> result = 4 * (a if (a != b) else b ** 2) / 2
>>> result
10.0
The condition to check here is whether a is not equal to b. As a equals 5 and b equals 8, they’re definitely not equal, so the condition is met. This entails using the value of a, which is 5, in the calculations:
4 * 5 / 2 = 10.0
Now, let’s make the two variables equal:
>>> a = b = 5
>>> result = 4 * (a if (a != b) else b ** 2) / 2
>>> result
50.0
Now the condition is not met, so b ** 2 is chosen for the calculations:
4 * 5 ** 2 / 2 = 4 * 25 / 2 = 50.0