Syntax
Let’s discuss the syntax of the Python ternary operator first. The syntax is as follows:
While using the ternary operator, first we write the name of the variable that value is to be checked in the condition. The on_flase statement is executed when the given condition is not true.
Examples
Now let’s see some examples to understand the use of the ternary operator. In the below given example, we are comparing two number values with the ternary operator.
num1=5
#declaring a num2 variable
num2=10
#using the ternary operator to check the highest value
result= num1 if num1>num2 else num2
print("The highest value is: ",result)
Output
The same example can also be implemented with the if-else statement. The ternary operator performs the job in a single line; however, the if-else statement uses multiple code lines for the same task. Let’s implement the above given example with the if-else statement.
num1=5
#declaring a num2 variable
num2=10
#implementing the if else statement
if(num1>num2):
result=num1
else:
result=num2
#printing the highest value
print("The highest value is: ",result)
Output
In the output, it can be seen that we get a similar output to the ternary operator.
The nested ternary operator can also be implemented. Let’s implement the nested ternary operator in our Python script.
num1=5
#declaring a variable num2
num2=10
#implementing nested ternary operator
print ("num1 is greater than num2" if num1>num2 else "num2 is greater than num1"
if num1==num2 else "Both numbers are not equal")
Output
Ways to implement the Python ternary operator
There are different ways to implement the Python ternary operator. We can implement the Python ternary operator using tuples, dictionaries, and lambda functions. Let’s implement the ternary operator using a tuple. We have created two number variables num1, and num2, and stored the random in these variables. The random numbers in Python are created using the random() function. The random() function is present in the random module.
num1=random.random()
num2=random.random()
#implementing the ternary operator
print((num1, num2) [num1>num2])
Output
From the output, we cannot determine that either it’s num1 or num2 value. Let’s implement the above code in the following way:
num1=random.random()
num2=random.random()
print((f"num1:{num1}", f"num2:{num2}") [num1>num2])
Output
Alright! Now let’s implement the ternary operator using Python dictionary and lambda function.
num1=random.random()
num2=random.random()
#using Python dictionary
print("Using Python dictionary:")
print(({True:f"num1:{num1}",False:f"num2:{num2}"}[num1>num2]))
#using lambda function
print("Using lambda function:")
print((lambda: f"num1:{num1}", lambda: f"num2:{num2}")[num1>num2]())
Output
Conclusion
Ternary operators are Python built-in operators that evaluate the given condition. It works like the if-else statement. This article explains the Python ternary operator in detail.