2026-03-23
last update: 2026-03-23
The Python Ternary Operator
My most recent Python dicovery is the ternary operator.
The ternary operator returns one of two values, based on the truthiness of a Boolean expression.
value_if_true if boolean_expression else value_if_false
Here's an example without the ternary operator, using an if-statement.
def odd_or_even(x):
if x % 2:
return "Odd"
else:
return "Even"
Here's the same function, using the ternary operator.
def odd_or_even(x):
return "Odd" if x % 2 else "Even"
Smart and succinct!