The Python Ternary Operator (One-Line if-else)

Introduction

The Python ternary operator provides a short and expressive way to write conditional expressions, which are pieces of syntax that results in a value, such as the number 1. The ternary operator allows you to create an expression that assumes one value if a condition is true, and another if it’s false.

The ternary operator is also referred to as the “conditional expression” because of what it does, and “one-line if-else” / “single-line if-else” because its syntax looks like an if-else that’s been compressed to one line.

The ternary operator is particularly useful when you need to make a concise decision and assign a value based on a condition.

Basic Python Ternary Operator Syntax

The basic syntax of the Python ternary operator consists of the following:

value_if_true if condition else value_if_false
  • condition: A boolean expression that determines which value will be chosen.
  • value_if_true: The resulting value when the condition is true.
  • value_if_false: The resulting value when the condition is false.

All of the above can be any expressions that result in a value such as literals (e.g. 1), function calls (e.g. round(x)), and the result of other operators (e.g. x + y). The condition can also be any expression, since all values have a boolean equivalent, truthy or falsy value.

The ternary operator draws its name from the fact that it must operate on three values to produce its result, while other programming language operators require only one (e.g. !) or two (e.g. +).

Using the Ternary Operator for Assignment

The most common use of the ternary operator is for conditional assignment. The following example assigns a value based on whether the dog is Snoopy or not.

Example:

dog_name = input("Please enter the dog's name: ")
number_of_treats = 5 if dog_name == "Snoopy" else 3

print(f"{dog_name} will get {number_of_treats} treats.")

Output:

Please enter the dog's name: Snoopy
Snoopy will get 5 treats.

The code in the example above determines how many treats a dog will get. Snoopy will get five, but other dogs only three. (Still not fair!) The program works by prompting the user to input the dog’s name on line 1. Then, the ternary operator on line 2 assigns the number of treats depending on whether the dog’s name is “Snoopy” or not.

Embedding the Ternary Operator Within Other Expressions

The ternary operator can also be embedded within other expressions, allowing you to use the result of the ternary operation as part of a larger computation.

Example:

dog_name = input("Please enter the dog's name: ")
number_of_weekly_treats = 7 * (5 if dog_name == "Snoopy" else 3)

print(f"{dog_name} will get {number_of_weekly_treats} treats for the week. Stock up now!")

Output:

Please enter the dog's name: Snoopy
Snoopy will get 35 treats for the week. Stock up now!

In the example above, the 5 if dog_name == "Snoopy" else 3 expression still provides the logic that gives Snoopy more treats using the ternary operator. However, now the example calculates the number of weekly treats, and therefore, the result of the ternary operator is multiplied by seven. The complete calculation of the number of treats given in a week is therefore calculated the full expression, 7 * (5 if dog_name == "Snoopy" else 3), assigned to number_of_weekly_treats. Ultimately, Snoopy will receive 7 \times 5 = 35 treats in a week, and other dogs 7 \times 3 = 21.

The parentheses in the full expression are necessary to arrive at the correct calculation. If they were to be omitted, i.e. 7 * 5 if dog_name == "Snoopy" else 3, the 7 would be strictly associated with the 5, because the ternary operator is low on the operator precedence order. This would give Snoopy 35 weekly treats, but other dogs, to their severe disappointment, only 3.

Ternary Operator vs. One-Line if

The ternary operator is similar to the Python one-line if statement because they are both conditionals that span one line of code. However, the one-line if does not support an else clause, and the ternary operator does have an else. For these reasons, some mistake the ternary operator for being a version of the one-line if, but with an else clause. That is not the correct because of a fundamental difference between them.

The ternary operator is an expression, which always results in a value (such as a number, string, or object), whereas the one-line if is a statement that does something but has no resulting value. Let’s see the implications of this next.

Because the ternary operator is an expression that must result in a value, it cannot operate on anything that has no value. There must be a value both when the condition is true and when the condition is false, consequently, it can always evaluate to something.

For example, in Python, variable assignment with the equal sign = is a value-less statement. And using it within the ternary operator gives a syntax error.

Example:

(x = 5) if dog_name == "Snoopy" else 3  # Does not work! Syntax error!
5 if dog_name == "Snoopy" else x = 3  # Also has a syntax error.

Note that if the parentheses are taken out of the example in line 1, it’s valid syntax, but it is interpreted differently. x = 5 if dog_name == "Snoopy" else 3 means “assign to x the result of the whole ternary operator, which could be 5 or 3.”

On the other hand, the one-line if can execute an assignment statement, as in line 3 of the example below.

Example:

number_of_treats = 3
dog_name = "Snoopy"
if dog_name == "Snoopy": number_of_treats = 5

print(number_of_treats)

Output:

5

But since the one-line if has no resulting value, it cannot be assigned as a whole to a variable, nor embedded within any expression, like the ternary operator expression can.

Example:

number_of_treats = if dog_name == "Snoopy": 5  # Does not work! Syntax error!

The example above has a syntax error because it attempts to assign the value of the if statement to the variable number_of_treats.

Nested Ternary Operators

It’s possible to nest ternary operators to handle more complex conditions. However, it’s crucial to maintain readability and avoid excessive nesting to ensure code clarity.

Example:

x = float(input("Please enter a number: "))
sign = "zero" if x == 0 else "positive" if x > 0 else "negative"

print(f"Your number is {sign}.")

Output:

Please enter a number: -1
Your number is negative.

Output:

Please enter a number: 0
Your number is zero.

Output:

Please enter a number: 10
Your number is positive.

In the example above, the program prompts the user to input a number, which is stored in the variable x. The ternary operators on line 3 then determine the sign of the number. It first determines whether the number equals 0, and if it is, it evaluates to the string “zero”. Then, the nested ternary operator determines if the number is greater than 0. If it is, it evaluates to “positive”, and otherwise to “negative”.

Summary & Reference for the Python Ternary Operator

The Python ternary operator provides a concise way to express conditional logic. It allows you to create an expression that assumes one value if a condition is true, and another if it’s false.


The basic syntax of the ternary operator is as follows:

value_if_true if condition else value_if_false

Here is an example of using the ternary operator for conditional assignment:

umber_of_treats = 5 if dog_name == "Snoopy" else 3

The ternary operator can be embedded within expressions, allowing for concise conditional computations:

number_of_weekly_treats = 7 * (5 if dog_name == "Snoopy" else 3)

The Python ternary operator is different from the one-line if statement not only because it has an else part but also because it must operate on expressions that have values and does not support value-less statements, such as assignment with =.

5 if dog_name == "Snoopy" else x = 3  # Does not work! Syntax error!

Nested ternary operators can be employed for more complex conditions, but readability should be prioritized.

sign = "zero" if x == 0 else "positive" if x > 0 else "negative"