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: 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: In this example, energy is -1 which is less than 0. So game_over is True.
Python Ternary Operator: Syntax and Examples
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: 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. Putting it all together, we have the following using Python’s ternary operator. 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. 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(
Similarly, when casting Boolean to integers, we have the following: 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: 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. 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. 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?
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.
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. 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. 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. 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:
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: Given the difficulty score, you can get its difficulty level using the Python ternary operator as shown: The ternary operator expression in the above code block is of the following form: Though concise, it is a bit difficult to read and parse. The following image shows how the control flow occurs in this case. 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. 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.