What is the ternary operator in Python?

The ternary operator is a way of writing conditional statements in Python. As the name ternary suggests, this Python operator consists of three operands.

The ternary operator can be thought of as a simplified, one-line version of the if-else statement to test a condition.

svg viewer

Syntax

The three operands in a ternary operator include:

  • condition: A boolean expression that evaluates to either true or false.
  • true_val: A value to be assigned if the expression is evaluated to true.
  • false_val: A value to be assigned if the expression is evaluated to false.
var = true_val if condition else false_val

The variable var on the left-hand side of the = (assignment) operator will be assigned:

  • value1 if the booleanExpression evaluates to true.
  • value2 if the booleanExpression evaluates to false.

Example

Let’s write a Python code snippet to check if an integer is even or odd.

# USING TERNARY OPERATOR
to_check = 6
msg = "Even" if to_check%2 == 0 else "Odd"
print(msg)
# USING USUAL IF-ELSE
msg = ""
if(to_check%2 == 0):
msg = "Even"
else:
msg = "Odd"
print(msg)

The above code is using the ternary operator to find if a number is even or odd.

  • msg will be assigned “even” if the condition (to_check % 2 == 0) is true.
  • msg will be assigned “odd” if the condition (to_check % 2 == 0) is false.

Note: Every code using the if-else statement cannot be replaced with the ternary operator. For instance, if-else statements with more than 2 cases.

Copyright ©2024 Educative, Inc. All rights reserved