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.

Syntax

expression1 if boolean_expression else expression2
  • A boolean_expression evaluates to either true or false.
  • If the resultant value of boolean_expression is true, expression1 will be executed.
  • And, if the resultant value of boolean_expression is false, expression2 will be executed.
  • As the name suggests, it accepts 3 operands (boolean_expression, expression1, and 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 a & b.
  • 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(and, or, not)

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

Vishnu Damwala
Vishnu Damwala

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳