Coding

# Ternary Operator in Python Ternary operators also referred to as conditional expressions are operators that evaluate something supported a condition being true or false. it had been added to Python in version 2.5.

It simply allows to check a condition during a single line replacing the multi line if-else making the code compact.

## 1.Simple Method to use ternary operator:

``````# Program to demonstrate conditional operator
a, b = 10, 20

# Copy value of a in min if a < b else copy b
min = a if a < b else b

print(min) ``````
``````Output:
10``````

## 2.Direct Method by using tuples, Dictionary and lambda

``````# Python program to demonstrate ternary operator
a, b = 10, 20

# Use tuple for selecting an item
print( (b, a) [a < b] )

# Use Dictionary for selecting an item
print({True: a, False: b} [a < b])

# lamda is more efficient than above two methods
# because in lambda  we are assure that
# only one expression will be evaluated unlike in
# tuple and Dictionary
print((lambda: b, lambda: a)[a < b]()) ``````
``````Output:
10
10
10``````

## 3.Ternary operator can be written as 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 > b else "b is greater than a")

# Python program to demonstrate nested ternary operator
a, b = 10, 20
if a != b:
if a > 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:

• First the given condition is evaluated (a < b), then either a or b is returned supported the Boolean value returned by the condition
• Order of the arguments within the operator is different from other languages like C/C++ (See C/C++ ternary operators).
• Conditional expressions have rock bottom priority among set all Python operations.
READ  Java Algorithm - Topological Sorting

## Method used prior to 2.5 when ternary operator was not present:

In an expression just like the one given below, the interpreter checks for the expression if this is often true then on_true is evaluated, else the on_false is evaluated.

### Example :

``````# Program to demonstrate conditional operator
a, b = 10, 20

# If a is less than b, then a is assigned
# else b is assigned (Note : it doesn't
# work if a is 0.
min = a < b and a or b

print(min) ``````
``````Output:
10`````` X