Python Ternary Operator

The ternary operator is a one-line if statement.

Very handy for simple conditions.

This is how it looks:

<expression> if <condition> else <expression>

Consider the following Python code:

a = 25
b = 50
x = 0
y = 1

result = x if a > b else y

print(result)
1

Here we use four variables, a and b are for the condition, while x and y represent the expressions.

a and b are the values we are checking against each other to evaluate some condition, in this case, we are checking if a is greater than b.

If the expression holds true, i.e., a is greater than b then the value o x will be attributed to result which will be equals to 0.

However, if a is less than b, then we have the value of y assigned to result, and result will hold the value 1.

Since a is less than b, 25 < 50, result will have 1 as final value from y.

The easy way to remember how the condition is evaluated is to read it in plain English.

Our example would read: result will be x if a is greater than b otherwise y.