What is the Ternary Operator in Python

Python ternary operator (conditional expression) is a “shorter way to write an if-else statement in a single line”. It allows you to return a value based on a condition.


value_if_true if condition else value_if_false


x = 19
y = 21

# Using a ternary operator to determine the minimum value
minimum = x if x < y else y

print("Minimum value:", minimum)


Minimum value: 19

In this example, the ternary operator checks if x is less than y. If the condition is true, it returns x; otherwise, it returns y. The result is stored in the minimum variable, which is then printed.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.