Main Tutorials

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")

Output


Odd

if n = 2


Even

1.2 Can’t assign to conditional expression.


## we can't use syntax as follows
a = 5 if True else a = 6

Output


      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)

Output


6

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")

Output


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:


(get_this_if_false, get_this_if_true)[condition]

Examples:


n = 20
canVote = (False, True)[n >= 18]
print(canVote)

Output


True

n = 10
canVote = (False, True)[n >= 18]
print(canVote)

Output


False

References

About Author

author image
I am a Pythoneer currently studying 3rd year in my Computer Science course. I will be a computer science graduate in 2 years. I am very fond of Python and Programming. I love to learn new technologies and enthusiastic about sharing my knowledge across the programming community.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
brent f
4 years ago

Thank you for explicitly explaining the form of the tuple expression. Experimenting lead me to believe that in (a,b)[some_test] that a was associated with False, but it’s nice that you took the time to clearly explain the tuple version of the ternary expression. I’ve been to 4 pages in the past half hour. Your’s is the only one that clarified this.