Python 3x Pandas Django

Ternary Operator


It is a shortcut for if-else and, simply allows to testing a condition in a single line replacing the multiline if-else making the code compact and more understandable.

Ternary operators are operators that evaluate something based on a condition being true or false and also known as conditional expressions.

Syntax

[on_true_value] if [expression] else [on_false_value]

Code Snippet

a = 100
b = 200

larger_number = a if (a > b) else b
print(larger_number)            #Output:200

print(a if (a > b) else b)      #Output:200

There are different ways to implement ternary operator

Using tuples

(on_false_value,on_true_value) [expression]

a = 100
b = 200

print((b,a) [a > b])            #Output:200
print((b,a) [a < b])            #Output:100

print((a,b) [a > b])            #Output:100
print((a,b) [a < b])            #Output:200

Using dictionaries

{False:on_false_value, True: on_true_value } [expression]

a = 100
b = 200

print({False: b, True: a}[a > b])   #Output:200
print({False: b, True: a}[a < b])   #Output:100

print({True: a, False: b}[a > b])   #Output:200
print({True: a, False: b}[a < b])   #Output:100

Using Lambdas

(lambda: on_false_value, lambda: on_true_value)[expression]()

a, b = 100, 200

print((lambda: a, lambda: b)[a>b]())  #Output:100

Ternary operator can also be written as nested if-else

Usual nested if-else

a, b = 100, 200

if a != b:
    if a > b:
        print("a is greater than b")
    else:
        print("b is greater than a")    #Output:b is greater than a
else:
      print("Both a and b are equal")

nested if-else with ternary operator

a, b = 100, 200

print ("Both a and b are equal" if a == b else
       "a is greater than b"    if a > b else
       "b is greater than a")      #Output: b is greater than a


If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!