Ternary Operator in Python

by | Jun 1, 2021 | Python

Introduction

A ternary operator defines a conditional expression, evaluates it and returns the values depending upon the condition satisfied.

Syntax:

[on_true] if [expression] else [on_false]

Points to remember:

  • Firstly, the expression ( e.g. x>y ) is computed returning Boolean output. The value is printed depending upon the output returned.
  • The order of argument given is different for different languages.
  • Ternary operator has the least priority.

Compare if-else statement with ternary operator

Program using if-else statement

x = 10
y = 3
if x > y:
    print("True")
else:
    print(False)

 

Program using ternary operator

x = 10
y = 3
print("True" if x > y else "False")

 

Explanation:

In both the programs firstly, we are computing the expression x>y and the Boolean True/False is returned depending upon the result. If the output is True, “True” is printed on the screen otherwise the output will be “False”.

In both cases, the output is True.

We can observe that by using the ternary operator the line of code is reduced to 1 and it is quite simple and understandable. It can be used to replace long nested if-else statements to reduce the complexity.

Ways to implement ternary operator

1.      Using tuple

x = 10
y = 3
#(if condition is false, if condition is true)
print(("False","True") [x > y])

Output:

True

2.      Using lambda

x = 10
y = 3
print((lambda: "False", lambda: "True")[x < y]())

 

Output:

False

3.      Using dictionary

x = 10
y = 3
print({True: 'True', False: 'False'}  [x > y])

Output:

True

4.      Nested Ternary operator

from random import random
num = random()
print("Picked number is less than zero" if num<0 else "Picked number is between 0 to 10" if num>=0 and num<=10 else "Picked number is between 10 to 20" if num>=10 and num<=20 else "Picked number is greater than 20")

Output:

Picked number is between 0 to 10.

The above code can also be written as :

from random import random
num = random()
if num<0:
    print("Picked number is less than zero")
elif (num>=0 and num<=10):
    print("Picked number is between 0 to 10")
elif (num>=10 and num<=20):
    print("Picked number is between 10 to 20")
else:
    print("Picked number is greater than 20")

 

Output:

Picked number is between 0 to 10.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.