Python - Ternary Operator
The ternary operator is a shorter version of an
if...else expression. It allows us to execute an expression if a condition is satisfied and another expression if the condition is not satisfied.
The ternary operator can be used to replace certain types of
if...else statements. It’s more regularly used with simple conditions. Using with multiple conditions comprises with readability.
It’s one of the most used operator, as it replaces the complete block of the
if...else statement with just simple as a single line.
Ternary Operator in Python
In this article, you will learn about the ternary operator and its use in Python; explained with the help of examples.
expression1 if boolean_expression else expression2
boolean_expressionevaluates to either
- If the resultant value of
expression1will be executed.
- And, if the resultant value of
expression2will be executed.
- As the name suggests, it accepts 3 operands (
expression2). Hence, the name ternary operator.
Example to identify whether number is positive or negative:
num = 12 print('Positive' if num > 0 else 'Negative') # Output # Positive
Example to find the largest number of two numbers
a = 12 b = 24 print('Both numbers are same' if a == b else ('A is larger than B' if a > b else 'B is larger than A') ) # Output # B is larger than A
- The above code for ternary operator includes condition(
a == b) for same value in both variables, next condition(
a > b) to identify larger of
- Some developers might prefer this way but it might be confusing for beginners.
- Adding more conditions in the ternary operator will cost its readability.
Note: Conditions can also include the use of Logical operators(
The syntax for a ternary operator is shorter than an
if...else statement, and sometimes it might make more sense to use it.
Hope you like this!
Keep helping and happy 😄 coding