Introduction to Python Ternary Operator
Python, one of the most user-friendly programming languages with very few syntactic hassles, is becoming one of the fastest-growing programming languages worldwide. A strong community of Python users and developers contribute to the betterment and growth of the language. Since its inception in 1991, Python has always been very dynamic in nature, and it is still evolving with time, with new features being added and old features getting depreciated.
The Ternary Operator came as an enhancement in the Python 2.5 version. It helps us to write conditional statements in Python in a single line. It can be thought of as a single line representation of an if-else block of code. Let us look into the syntax of the Ternary Operator and look at its application in more detail.
Syntax:
var = true_val if condition else false_val
There are three operands in a Ternary Operator
- condition: It is a Boolean expression that evaluates to either true or false.
- true_val: It is the value that is to be assigned if the expression is evaluated to be true.
- false_val: It is the value that is to be assigned if the expression is evaluated to be false.
The following figure will help to show the point:
Examples of Python Ternary Operator
Let us see a simple program of determining a number to be odd or even. We would first write using a normal if-else statement, and then we would use Ternary Operator to best appreciate its usage.
1. Using If-Else Block of Code
Code:
num=int(input("Enter number to check :"))
if(num%2==0):
msg=str(num)+"is an even number"
else:
msg=str(num)+"is an odd number"
print(msg)
Output:
Below is for the odd number,
2. Using Ternary Operator
Code:
num=int(input("Enter number to check :"))
msg=str(num)+"is an even number" if num%2==0 else str(num)+"is an odd number"
print(msg)
Output:
Below is for the odd number,
In the above examples, we see that the same functionality can be achieved both if-else blocks and also by means of a Ternary Operator. Using the if-else block, it takes 6 lines of code, while using Ternary Operator, it takes only 3 lines of code. It takes half the time and effort to achieve the same functionality. Thus for complex programs, usage of a Ternary Operator should be a must.
Usages of Ternary Operator
Here are the other usages of Python Ternary Operators given below:
1. Using Python Tuples
Code:
a=3
print(("Odd","Even") [a%2==0])
Output:
Below is the other example to check it,
Code:
a=24
print(("Odd","Even") [a%2==0])
Output:
In the above example, we are using Ternary Operator using Python Tuples. The condition for determining odd or even is provided within square brackets, i.e. [a%2==0] and the values based on the condition are to be passed within the tuple, the first value, i.e. “Odd” in this case is for the negative scenario and the second value, i.e. “Even” in this case for the positive scenario.
2. Using Python Dictionary
Code:
a=40
print({True:"Even", False: "Odd"} [a%2==0])
Output:
Below is the other example to check it,
Code:
a=15
print({True:"Even", False: "Odd"} [a%2==0])
Output:
In the above example, we are using Ternary Operator using Python Dictionary. The condition for determining odd or even is provided within square brackets, i.e. [a%2==0], and the values based on the condition are to be passed within a Dictionary. The keys would be True and False, respectively, and the values for the respective keys are to mention.
Here when the condition a%2==0 is true, then a is an Even number, so the value for the key “True” is “Even”, and conversely, the value for the key “False” is “Odd”.
3. Using Python Lambda Function
Code:
a=3
print((lambda:"Odd", lambda: "Even") [a%2==0]())
Output:
Below is the other example to check it,
Code:
a=20
print((lambda:"Odd", lambda: "Even") [a%2==0]())
Output:
In the above example, we are using Ternary Operator using the Python lambda function. The condition for determining odd or even is provided within square brackets, i.e. [a%2==0], and the values based on the condition are to be passed as shown above. The first value is for the negative scenario, and the second value is for the positive scenario.
Here, when a%2==0 is true, then an Even number, hence “Even” is given as the second value, and “Odd” is given as the first value.
Limitation of Ternary Operators
Here are some of the limitations of the ternary operator explained below:
- Though Ternary Operators can be used to replace the if-else statement, it is only limited to usage for a single if-else statement.
- For multiple if-else statements, the Ternary Operators are not used.
- Though a Ternary Operator can be used as a nested if-else like follows for a condition having three probable values.
Ternary Operator as Nested If-Else
Code:
num1, num2=5,3
print("Both num1 and num2 are equal" if num1==num2 else "num1 is greater than num2" if num1>num2 else "num2 is greater than num1")
Output:
This is a simple example of comparing two numbers are determining which one is greater than the other. It might look like an example that has only two values as output. “num1 greater than num2” and “num2 greater than num1”. But for better programming practice, we must consider the scenario when both the numbers would be equal thus;, there is a total of 3 scenarios. To accommodate all three scenarios, we have to use Ternary Operator as a nested if-else.
Conclusion
In the following article, we have discussed Ternary Operator, one of Python’s most important tools, which has reduced code size, replacing conventional if-else statements, thus resulting in better readability of the code. The different usages of Ternary operators and their syntax and examples have also been discussed in detail.
Recommended Articles
This is a guide to Python Ternary Operator. Here we discuss the syntax and example of Python Ternary Operator along with its usage and limitations. You can also go through our other related articles to learn more –
40 Online Courses | 13 Hands-on Projects | 215+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses