Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

conditional
if-else
loop
python

What is the ternary operator in Python?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

conditional
if-else
loop
python
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring