Does Python have a ternary conditional operator ?

Explanation

Yes, Python has a ternary conditional operator. And it was added in version 2.5. So The expression syntax is:

a if condition else b

Here always the first condition is evaluated. After that exactly one of either a or b is evaluated. Anyone from both can be chosen. It is returned on the basis of the Boolean value of the condition.  So that if the  condition evaluates to be True At that time  a is evaluated and returned but b is ignored. Or vise versa that means when b is evaluated and returned but a is ignored.

This allows short-circuiting because when the condition is true only a is evaluated and b is not evaluated at all. but when the condition is false only b is evaluated and a is not evaluated at all. So that it depends on the condition. Whether the condition is true or false. 

For example:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

 Here one thing to note is that conditional statements are expressions and not a statement. So this means that we can’t use assignment statements or other statements within a conditional expression.

>>> pass if False else x = 3
  File "<stdin>", line 1
    pass if False else x = 3
          ^
SyntaxError: invalid syntax

 And one can use conditional expressions to assign a variable. As shown below:

x = a if True else b

 Now we will think of a scenario that we have to switch the conditional expression between two values. So at that time, it will be very useful when we have one value and another. 

And if one needs to use statements, at that time one has to use a normal if statement instead of using a conditional expression.

So it is proved that Python has a ternary conditional operator.

 

Also read, Both merge sort and quick sort uses divide and conquer paradigm to sort the unsorted list.

Share this post

Leave a Reply

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