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.
Syntax
The three operands in a ternary operator include:
- condition: A
booleanexpression that evaluates to eithertrueorfalse. - 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:
value1if the booleanExpression evaluates totrue.value2if the booleanExpression evaluates tofalse.
Example
Let’s write a Python code snippet to check if an integer is even or odd.
# USING TERNARY OPERATORto_check = 6msg = "Even" if to_check%2 == 0 else "Odd"print(msg)# USING USUAL IF-ELSEmsg = ""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.
msgwill be assigned “even” if the condition (to_check % 2 == 0) istrue.msgwill be assigned “odd” if the condition (to_check % 2 == 0) isfalse.
Note: Every code using the
if-elsestatement cannot be replaced with the ternary operator. For instance,if-elsestatements with more than 2 cases.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved