Skip to content
Home / Fundamentals

Ternary conditional operator in Python

The ternary conditional operator is a shorthand way to write an if-else statement in Python. It can be especially useful for concisely expressing simple conditional logic in a single line of code.

Here's the basic syntax of the ternary operator:

value_if_true if condition else value_if_false

The condition is a boolean expression that is evaluated first. If it is True, then the expression returns value_if_true; otherwise, it returns value_if_false.

Here's an example of using the ternary operator to assign a value to a variable based on a condition:

x = 10
y = 20
max_value = x if x > y else y
print(max_value)  # Output: 20

In this example, max_value is assigned the value of y because x > y is False.

You can also use the ternary operator in a more complex expression, such as the following:

x = 10
y = 20
z = 30
max_value = x if x > y and x > z else y if y > z else z
print(max_value)  # Output: 30

In this example, the ternary operator is used to find the maximum value of x, y, and z. The first part of the expression (x if x > y and x > z) checks if x is the maximum value. If it is, then x is returned. If not, the second part of the expression (y if y > z) is evaluated, and if y is the maximum value, then y is returned. Otherwise, the final part of the expression (z) is returned.

You can also use the ternary operator to return a value based on a condition within a function, like this:

def get_max_value(x, y, z):
  return x if x > y and x > z else y if y > z else z

max_value = get_max_value(10, 20, 30)
print(max_value)  # Output: 30