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.

Syntax

value_if_true if condition else value_if_false

Example

x = 19
y = 21

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

print("Minimum value:", minimum)

Output

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.