This guide will teach you how to use the ternary operator in Python. You’ll learn the syntax and code several examples to understand how it works.

We’ll start by reviewing how the if-else conditional statement works and then learn how to write an equivalent expression using the ternary operator.

Next, we’ll code a few examples and then learn how to emulate the behavior of Python’s ternary operator using a Python tuple and dictionary. Finally, we’ll review a few use cases when you should prefer using the ternary operator.

Let’s begin!

The If-Else Statement in Python: A Review

You can code along by starting a Python REPL or in Geekflare’s online Python editor.

The generic syntax of the if-else statement in Python is as follows:

if condition:
    # do this
else:
    # do this

In the above snippet, condition denotes the condition to be checked. If the condition evaluates to True, then the if block is triggered. If the condition evaluates to False, then the statements inside the else block are executed.

Here’s an example where the game_over variable is assigned a Boolean value depending on whether or not the value of energy is less than or equal to zero.

  • If energy <= 0, game_over is True.
  • Else, game_over is False.

The following code snippet shows how to do this using the if-else conditional statements:

energy = -1

if energy <= 0:
    game_over = True
else:
    game_over = False

print(game_over)
# True

In this example, energy is -1 which is less than 0. So game_over is True.

Python Ternary Operator: Syntax and Examples

<img alt="python-ternary-operator-1
" data- data-src="https://kirelos.com/wp-content/uploads/2023/01/echo/7-1-1500×844.png" data- decoding="async" height="422" src="data:image/svg xml,” width=”750″>

Python has a ternary operator that works a lot like the ternary conditional operator in languages like C and C . The general syntax to use it is as follows:

expression1 if condition else expression2

Let’s parse the above syntax:

  • condition: The condition to check for.
  • expression1: The expression to evaluate if the condition is True.
  • expression2: The expression to evaluate if the condition is False.

Now, we’ll identify what expression1, expression2, and condition should be from the if-else version of the code.

<img alt="ternary-op-ex1" data- data-src="https://kirelos.com/wp-content/uploads/2023/01/echo/ternary-op-ex1.png" data- decoding="async" height="212" src="data:image/svg xml,” width=”614″>

Putting it all together, we have the following using Python’s ternary operator.

game_over = True if energy <= 0 else False
print(game_over)
# True

Let’s code another example. Suppose you run a bookstore and you give the readers a discount on their purchase depending on how frequently they’ve visited your store in the last one year.

Let numVisits denote the number of visits.

  • If numVisits > 7, the discount percentage, discount_perc is 20.
  • Else, discount_perc is 5.

We use the ternary operator to assign value to the discount_perc variable.

numVisits = 10

discount_perc = 20 if numVisits > 7 else 5

print(discount_perc)
# 20 (as numVisits = 10 which is > 7)

Next, we’ll learn how to emulate the ternary operator using a Python tuple and a dictionary.

Emulating the Ternary Operator with Python Tuple

Like all iterables in Python, tuples follow zero indexing. So if you have two elements in a tuple, tuple_name[0] denotes the first element in the tuple and tuple_name[1] gives the second element in the tuple.

The basic data types in Python are integer, float, string, and Boolean. Python supports type casting that lets you represent a particular data type by its equivalent representation in another data type.

Start a Python REPL and run the following examples. If you try converting integers to Booleans, you’ll notice the following:

  • bool(0) is False.
  • bool() returns True.
>>> bool(0)
False
>>> bool(1)
True
>>> bool(-1)
True
>>> bool(10)
True

Similarly, when casting Boolean to integers, we have the following:

>>> int(True)
1
>>> int(False)
0

Putting together the type casting and indexing, we can do as follows:

  • Element at index 0 in the tuple: The value to be used when the condition is False.
  • Element at index 1 in the tuple: The value to be used when the condition is True.

Uisng the above, we have the following:

>>> numVisits = 10
>>> discount_perc = (5,20)[numVisits > 7]
>>> discount_perc
# 20

Here, the condition numVisits > 7 is True as numVisits is 10. Because int(True) is 1, the value of discount_perc is 20, the element at index 1.

Emulating the Ternary Operator with Python Dictionary

You can set True and False as the keys of the dictionary. And you can set expression1 and expression2 as the values corresponding to the keys True and False, respectively.

some_dict = {True: expression1,
             False: expression2
            }

What do you do next? Now if you use some_dict[condition], expression1 corresponding to the True key is evaluated if the condition is True. And expression2 is evaluated when the condition is False.

Let’s code the discount_perc example (again) but this time using a Python dictionary.

>>> numVisits = 10
>>> discount_dict = {True: 20, False:5}
>>> discount_perc = discount_dict[numVisits > 7]
>>> discount_perc
# 20

Here, numVisits = 10 which is greater than 7. Therefore, the condition numVisits > 7 is True. So discount_dict[numVisits > 7] evaluates to discount_dict[True] which is the value 20.

Should You Always Use the Python Ternary Operator?

<img alt="Should You Always Use the Python Ternary Operator" data- data-src="https://kirelos.com/wp-content/uploads/2023/01/echo/qs.png" data- decoding="async" height="445" src="data:image/svg xml,” width=”494″>

So far, we’ve learned how to use the ternary operator. But should we always use the ternary operator? Well, the ternary operator may not be the best choice for all use cases. This section breaks down when you should prefer using the ternary operator over if-else statements. We’ll also cover when we should consider using the if-else statement instead of the ternary operator.

More Concise Than If-Else Blocks

As mentioned, in Python, the ternary operator expression is more concise than the if-else statement. Therefore, you can use it to check for conditions and evaluate expressions conditionally on the fly.

In the following example, nums is a list of 100 randomly generated integers. For each of the 100 numbers, we check if it is odd or even. And this evaluation occurs inline inside the f-string.

import random

nums = [random.choice(range(100)) for i in range(10)]

for num in nums:
    print(f"{num} is {'even' if num%2==0 else 'odd'}")
# sample output

0 is even
56 is even
6 is even
53 is odd
62 is even
7 is odd
8 is even
77 is odd
41 is odd
94 is even

The Ternary Operator Requires the Else Clause

When you’re using the if-else conditional statements, the else clause is optional. Let’s take an example. The game_over variable is set to True if the energy drops to a value less than or equal to zero.

However, if the energy is greater than zero, the game_over variable is never initialized. So you’ll run into errors if you try to access the game_over variable.

energy = 5
if energy <= 0:
    game_over = True

print(f"Is the game over? {game_over}")
Traceback (most recent call last):
  File "ternary_op.py", line 39, in 
    print(f"Is the game over? {game_over}")
NameError: name 'game_over' is not defined

One way to fix this is to set game_over to False initially and update it to True if the energy level is less than or equal to zero.

energy = 5
game_over = False
if energy <= 0:
    game_over1 = True

print(f"Is the game over? {game_over}")

However, when using the Python ternary operator equivalent of the above, the else clause is not optional. The ternary operator requires the expression to be evaluated when the condition is False.

game_over = True if energy <= 0 else False

If you change the above to game_over = True if energy <= 0 by removing the else part, you’ll run into syntax error, as shown:

File "ternary_op.py", line 42
    game_over = True if energy <= 0
                                  ^
SyntaxError: invalid syntax

To Check for Multiple Conditions, Use If-Else Statements

Consider the example: Every question in a set of coding interview questions has an associated difficulty score. Depending on this score, we assign one of the three difficulty levels: easy, medium, or hard, to a particular question. Suppose we have the following:

Score Difficulty Level
Less than 10 easy
Between 10 and 20 medium
Greater than 20 hard

Given the difficulty score, you can get its difficulty level using the Python ternary operator as shown:

score = 12

difficulty_level = "easy" if score  20 else "medium"

print(difficulty_level)
# medium

The ternary operator expression in the above code block is of the following form:

expression1 if condition1 else expression2 if condition2 else expression3

Though concise, it is a bit difficult to read and parse. The following image shows how the control flow occurs in this case.

<img alt="ternary-operator-example" data- data-src="https://kirelos.com/wp-content/uploads/2023/01/echo/image-5-1500×937.png" data- decoding="async" height="469" src="data:image/svg xml,” width=”750″>

The following code snippet shows an equivalent implementation using if-else statements. As seen, the control flow is much easier to understand, and the code is more readable.

if score  20:
    difficulty_level="hard"
else:
    difficulty_level="medium"

print(difficulty_level)

Therefore, when you have multiple conditions, you should use the if-else blocks instead of the ternary operator. This ensures that the code is easy to read and understand.

Also, when you need to execute multiple statements—depending on whether the condition is true or false—you should consider using the if-else statement.

Conclusion

Here is a recap of what you have learned in this tutorial.

  • In Python, the ternary operator can be used with the following syntax: expression1 if condition else expression2.
  • You can emulate the behavior of the ternary operator using Python tuples and dictionaries.
  • While the ternary operator can be a more concise alternative to the if-else blocks, you should ensure that the code is readable. To improve the readability of code, you can use the if-else statements instead of the ternary operator, especially when you need to chain multiple conditions.

Next, learn to check out the tutorial on equal and not equal operators in Python.