Python Ternary Conditional Operator
This article shows you how to write Python
ternary operator, also called conditional expressions.
<expression1> if <condition> else <expression2>
expression1 will be evaluated if the condition is true, otherwise
expression2 will be evaluated.
1. Ternary Operator
1.1 This example will print whether a number is odd or even.
n = 5 print("Even") if n % 2 == 0 else print("Odd")
n = 2
1.2 Can’t assign to conditional expression.
## we can't use syntax as follows a = 5 if True else a = 6
File "<ipython-input-4-66113f0b2850>", line 2 a = 5 if True else a = 6 ^ SyntaxError: can't assign to conditional expression
Instead, assign value to a variable as follows.
## we can use it as follows a = 5 if False else 6 print(a)
2. Multilevel Ternary Operator
Till now, we have used the ternary operator with one condition only. Let’s see how to use it for multiple conditions. Suppose we have to check for two conditions, one is for even, and the other is for the multiple of four. Try to write the code for the condition using the ternary operator.
n = int(input("number: ")) print("Satisfied") if n % 4 == 0 else print("Destroyed1") if n % 2 == 0 else print("Destroyed2")
number: 3 Destroyed2 number: 6 Destroyed1 number: 8 Satisfied
Python executes the rightmost conditional operator first. So, in the above program, it checks whether the number is even or not first. If it’s Even then, it goes to check whether it is a multiple of four or not.
3. Python Tuple
We can use
Tuple as ternary operator, it works like this:
n = 20 canVote = (False, True)[n >= 18] print(canVote)
n = 10 canVote = (False, True)[n >= 18] print(canVote)