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.
The three operands in a ternary operator include:
boolean
expression that evaluates to either true
or false
.true
.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
.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
.
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.