The ternary operator in Python is a shorthand way of writing an if-else
statement in a single line. It allows you to evaluate a condition and return one of two values based on whether the condition is True
or False
.
The syntax for the ternary operator is:
value_if_true if condition else value_if_false
Example:
x = 10
result = "Even" if x % 2 == 0 else "Odd"
print(result) # Output: Even
Explanation:
x % 2 == 0
is the condition being evaluated.- If the condition is
True
, the result will be"Even"
. - If the condition is
False
, the result will be"Odd"
.
This allows for more concise code when you need to make simple conditional decisions.