Python Ternary Operator with Example

FREE Online Courses: Knowledge Awaits – Click for Free Access!

Python is among the most user-friendly computer programming languages with few grammatical complexities and is quickly becoming one of the world’s fastest-growing computer languages. A vibrant community of Python users and developers contributes to the language’s improvement and growth. Python has always been quite dynamic from its birth in 1991, and it is continually developing with time, with new upgrades being added and old features being discarded.

A Python developer’s priority should always be to write short, clean, efficient, and understandable Python code. Ternary operators, which allow for a more concise manner of writing conditional statements in Python, can be utilized to do this. It was added as an enhancement in Python 2.5.

Today’s topic is Python Ternary Operator. In addition, we will go through an example and syntax of the Ternary Operator in Python. We will also learn about before and nested Python Ternary Operators. Finally, we will go over how to implement Ternary operators in Python.

Introduction to Python Conditional Statements

In Python, conditional statements conduct alternative computations or actions based on whether a given Boolean constraint evaluates to true or false. The if…else statement is how you execute this type of decision-making in a Python program. It enables the execution of a statement or collection of statements conditionally based on the value of an expression.

Assume we are developing an application that determines whether a customer is entitled to a 30% discount at a medical store. If the buyer is 65 or older, a discount should be given; otherwise, no discount should be granted. This program could be written using an if…else expression.

flow chart of python conditionals

What is Python Ternary Operator?

In the Python programming language, the Ternary Operator is a condition expression that allows developers to evaluate statements. The Ternary Operators perform an action based on whether the statement is True or False. As a result, these operators are shorter than a standard if-else statement.

Syntax of Python Ternary Operator with Example

Python’s ternary operators, as the name implies, require three operands to function. The Python ternary statement has the following syntax:

<variable> = <true_value> if <condition> else <false_value>

The three operands are as follows:

1. condition: A Boolean expression must be evaluated to determine whether it is true or false.

2. true_value: A value assigned if the condition is true.

3. false_value: A value to be assigned if the condition is false.

Ternary Operators are commonly used to determine the value of a variable. If the condition is True, the variable takes on the value “true value,” else it takes on the value “false value.”

Example for Ternary Operator Implementation

Let’s return to the earlier-mentioned example, where we wish to provide a consumer at the medical store a discount if they are 65 or older. Customers who are not 65 or older are not eligible for a discount.

Code and Output for if-else Implementation

To grasp the difference between the Python ternary operator and the if-else statement approach, let’s start with the if-else statement.

# Taking input of your age
a = int(input("Enter Your Age : "))
#if condition to check if age>=65 or not
if(a>=65):
 print("\nYay! 30% Discount!")
#if age<65
else:
 print("\nSorry! No Discount!")

Output if 67 is the input:

Enter Your Age : 67Yay! 30% Discount!

Code and Output for Ternary Operator Implementation
We can now use the syntax of the ternary expression to make this program much more compact.

# Taking input of your age
a = int(input("Enter Your Age : "))
# <result if cond. is T> if <cond.> else <result if cond. is F>
PythonGeeks_result = "\nYay! 30% Discount!" if (a>=65) else "\nSorry! No Discount!"
print(PythonGeeks_result)

Output if 78 is the input:

Enter Your Age : 78

Yay! 30% Discount!

Ways to implement Python Ternary Operator

Now that we understand how Python’s ternary operator works let’s look at how it pertains to Tuples, Dictionary, and Lambda.

Before we get there, let’s start with a simple program that finds the smaller of two user-input numbers. Using the ternary approach with Python’s Tuples, Dictionary, and Lambda functions helps to have a clear picture of what we want to achieve.

Here is a simple and easy Python program that uses the ternary operator method to find the smaller of two values.

# Take input of two numbers
a = int(input())
b = int(input())
# check which is smaller
PythonGeeks_result = a if a<b else b
print("Smaller Number is: ",PythonGeeks_result)

Output if a = 78 and b = 56 is the input:

Smaller Number is: 56

Code and Output for Python ternary operator with Tuples

Let’s look at how ternary conditions are applied to Tuples now. The syntax to remember when using the ternary operator with Tuples is:

(false_value,true_value)[condition]

# Take input of two numbers
a = int(input())
b = int(input())
# check which is smaller using tuples
# (if false,if true)[condition]
print("Smaller Number is: ",(b,a)[a<b])

Output if a = 74 and b = 86 is the input:

Smaller Number is: 74

Code and Output for Python ternary operator with Dictionary

Let’s look at how ternary conditions are applied to the Dictionary data structure.

# Take input of two numbers
a = int(input())
b = int(input())
# check which is smaller using dictionary
print("Smaller Number is: ",{True:a,False:b}[a<b])

If [a<b] is True, the True key’s value will be written in this scenario. Otherwise, if the condition is False, the value of the False key is printed.

Output if a = 44 and b = 86 is the input:

Smaller Number is: 44

Code and Output for Python ternary operator with the Lambda function

Surprisingly, using the Lambda function to build the ternary operator is more efficient than the other two techniques. This is because Lambda guarantees that just one expression will be evaluated. In the case of Tuple or Dictionary, however, both expressions are evaluated.

# Take input of two numbers
a = int(input())
b = int(input())
# check which is smaller using lambda
print("Smaller Number is: ",(lambda:b,lambda:a)[a<b]())

Output if a = 94 and b = 66 is the input:

Smaller Number is: 66

Implementation of Nested Ternary Operators

The term “nested” ternaries is a bit misleading because ternaries are so easy to write in a straight line that you never need to nest them with indent levels at all. They just read from top to bottom in a straight line, returning a value whenever they come across a true condition or the fallback.

There is no nesting to parse if you write ternaries correctly. It’s difficult to get lost when you’re following a straight line. Instead, we should term them “chained ternaries.”

Let’s make things easy to understand through an easy example.

# Take Input of Number
no = int(input())

# Nested Ternary Operators Implementation
PythonGeeks_result = "Negative Number" if no<0 else "Number is Zero" if no==0 else "Positive Number"

# Displaying the result
print("Result for ",no," : ",PythonGeeks_result)

Output if n = 90 is the input:

Result for 90 : Positive Number

Here, we check for the value of no (given by the user). If it falls shorter than 0, we print “Negative Number”; if its value equals 0, we print “Number is Zero.” Else, we print “Positive Number.” Take note of how we nested them.

Before the Birth of Ternary Operators

Before Ternary Operators were introduced, programmers used to use alternatives to the operators. Look at the example code below.

# Set value for a and b
a,b=45,89

# Return Greater of both numbers
PythonGeeks_result = (a>b) and a or b

# display result
print("Result for ",a," and ",b, " : ",PythonGeeks_result)

The program checks for two conditions, i.e., (a>b) and (a or b). Let’s understand both conditions one after another.

Condition 1: a>b

The condition will return “True” if the value of a>value of b, otherwise it returns “False.”

Condition 2: a or b

We already know that when “or” is applied to two numbers, it will always return the first number.

Now, this might look like b will never come as an answer. But don’t forget the “and” in between the two conditions. If a>b comes out to be “False,” then (a>b and a) comes out as “False,” and the value of b is returned as an answer.

Suppose we consider the value of “a” as 45 and “b” as 89. The first condition becomes “False” as 45<89. Then “False and a” becomes “False” along with this, the final condition “False or b” will return b as the answer (which is the larger value).

Limitations of Ternary Operators

Here are examples of the ternary operator’s restrictions, as stated below:
1. While Ternary Operators can replace the if-else statement, they are only valid for a single if-else statement.

2. Ternary Operators are not used for numerous if-else expressions.

3. Ternary Operator can be utilized as a nested if-else; however, as seen above, that’s only possible for a condition with three possible values.

Python Interview Questions on Ternary Operator

Q1. Is there a Ternary operator in Python?

Ans. Yes, it has been included in version 2.5. The syntax of the expression is as follows: an if condition else b. The condition is first assessed, and then exactly one of a or b is evaluated and returned based on the condition’s Boolean value.

Q2. What exactly is the Python ternary operator symbol?

Ans. Many C-like programming languages provide a ternary operator?:, which defines a conditional statement. This operator is recognized as the conditional operator in some languages. In Python, the ternary operator is simply a one-line version of the if-else expression. There is no such thing as a symbol.

Conclusion

The Python ternary operator provides a quick and easy way to build if-else sentences. It first analyses the supplied condition and then returns a value based on whether that condition is True or False.
In the following post, we addressed Ternary Operator, one of Python’s most effective tools, which has decreased code size by replacing typical if-else expressions, resulting in better code readability. The various applications of Ternary operators and their syntax and examples have been thoroughly addressed.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google | Facebook


Leave a Reply

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