Ternary operator in Python

Python Methods and Functions

Syntax:

 [on_true] if [expression] else [on_false] 
  1. A simple ternary operator method:

    # Program for demonstrating the conditional operator

    a, b = 10 , 20

     
    # Copy the value of a in minutes if a & lt; b still copy b

    min = a if a & lt; b else b

      

    print ( min )

      Output:  10 
  2. Direct method using tuples, dictionary and lambda

    # Python program for demonstration ternary operator

    a, b = 10 , 20

     
    # Use a tuple to select an element

    print ((b, a) [a & lt; b])

      
    # Use a dictionary to select an item

    print ({ True : a, False : b} [a & lt; b])

     
    # lamda is more efficient than the above two methods
    # because in the lambda we are sure that
    # only one expression will be evaluated unlike
    # tuple and dictionary

    print (( lambda : b, lambda : a) [a & lt; b] ())

     Output: 10 10 10 
  3. The ternary operator can be written as a nested if-else:

    # Python program to demonstrate nested ternary operator

    a, b = 10 , 20

     

    print ( "Both a and b are equal" if a = = b else "a is greater than b"

    if a & gt; b else "b is greater than a" )

    The above approach can be written like this:

    # Python program to demonstrate nested ternary operator

    a, b = 10 , 20

     

    if a ! = b:

    if a & gt; b:

    print ( "a is greater than b" )

    else :

    print ( "b is greater than a" )

    else :

    print ( "Both a and b are equal " )

      Output:  b is greater than a 


Important points: