Ternary Operator with examples in Python

Ternary Operator with examples in Python

Ternary Operator in Python

ternary operator,ternary operator python,conditional operator


In python ternary operator is used to return a value based on the result of a binary condition.  first It takes the binary value(condition) as an input, so it looks similar to an “if-else” condition block, and replace the multiple lines of if-else, to reduce the complexity.


Syntax of Simple Method 

we will compare this with a if-else through a piece of code

x, y = 4,3
if x>y :
      print ("x")
else :
      print ("y")

output :

x
    Now we will see same thing through the ternary operator

    x, y = 4,3
    print("x" if x>y else "y")

    output :

    x

      Using Ternary and Dictionary

      Now we will see the use of this operator directly in ternary and dictionary.

      a, b = 15, 22

      print( (b, a) [a < b] )  

      print({True: a, False: b} [a < b])

      print((lambda: b, lambda: a)[a < b]())

      output :
      15
      15
      15
        Lets see this approach separately 

        In Tuple

        a, b = random(), random()
        (b, a) [a>b]


        output :

        0.5497848117028667

        In Dictionary

         a, b = random(), random()
         {False: f"b:{b}", True: f"a:{a}"}[a>b]

        output :

        'a:0.8089581560973976'

        Nested Ternary Operator

        a, b = 15, 22
          
        print ("a and b are equal according to the condition" if a == b else "a is greater than b"
                if a > b else "b is greater than a") # to check the greatest

        output :

        b is greater than a 

        In this article i have explained about Ternary Operator.

        Next Article : Any and All in Python

        Recommended Post : 












        #python online
        #python programming
        #python list
        #learn python
        #python requests
        #introduction to data science in python
        #free python tutorial
        #learn python basics
        #python study
        #python and ai
        #python computer science
        #learn python step by step
        #best course to learn python
        #ternary operator
        #conditional operator
        #ternary operator in python






































        Post a Comment

        2 Comments

        If you have any doubt, Please let me know.