How to use Ternary Operator in Python?

How to use Ternary Operator in Python?

ยท

2 min read

Python is one of the fastest-growing programming languages worldwide. It's always being updated with new features. It is quite famous for its convenient one-liners. One such is the ternary operator. The ternary operator is available in most programming languages, so how can Python miss out on this amazing feature.

What is Ternary Operator?

The ternary operator helps you write conditional statements in one line. The syntax of the ternary operator is very easy to understand:

some_var = statement_one if conditional_exp else statement_two

where

  • statement_one will be selected if the conditional_exp is True
  • statement_two will be selected if the conditional_exp is False

Note: It is not necessary to assign the value evaluated from the ternary operator into a variable. It depends on the usage.

Examples

Basic Usage

Let us first see an example of an if-else condition:

order_value = 1070

if order_value >= 1000:
    discount = 10
else:
    discount = 5

In this example, we are evaluating the discount according to order_value. If the order_value is more than or equal to 1000, the discount will be 10%, otherwise, the discount will be 5%. The above example snippet can be rewritten using the ternary operator as:

order_value = 1070

discount = 10 if order_value >= 1000 else 5

Isn't that quite simple?

Nested Conditions

We can also the ternary operator for nested conditions. Let us first look at an example of nested if-else condition to find the largest among three numbers:

a, b, c = 10, 15, 13

if a >= b and a >= c:
    print(a)
elif b >= c:
    print(b)
else:
    print(c)

The code can be rewritten using two ternary operators as below:

a, b, c = 10, 15, 13

print(a) if a >= b and a >= c else print(b) if b >= c else print(c)

Thus we are able to use ternary operators to write nested conditions too. But honestly, the code sometimes becomes unreadable too.

Wrapping Up

In this short article, we learned about the Ternary Operator, what is its syntax and how to use it with examples.

Thanks for reading!

Did you find this article valuable?

Support Ashutosh Krishna by becoming a sponsor. Any amount is appreciated!

ย