Articles

Guide to Using Ternary Operator in Python

Learn how the ternary operator works in Python compared to if-else statements, its advantages and disadvantages, and some best practices for using it.

What are ternary operators in Python?

In Python, we often encounter situations where we need to make decisions based on certain conditions. For example, we may need to decide whether a user qualifies for a discount based on their purchase amount or determine if a student has passed an exam based on the marks obtained. Traditionally, we use if-else statements to handle these situations. However, Python provides us with an alternative called the ternary operator. The Python ternary operator is an efficient way to make quick conditional decisions based on a single expression.

In this article, we will discuss how the ternary operator works in Python compared to if-else statements, its advantages and disadvantages, and the best practices for using it.

Related Course

Learn PHP: Conditionals and Logic

Write programs that handle complex decision-making using the boolean data type, conditionals, and comparison and logical operators.Try it for free

How to use if-else statements in Python

Before we learn how to use the Python ternary operator, let’s go through the process of using if-else statements in Python.

If-else statements allow us to execute different code blocks depending on whether a particular condition is true or false.

In this example, we use the if-else statement to check if a user qualifies for a discount based on their purchase amount:

amount = 550
if (amount >= 500):
print("Eligible")
else:
print("Ineligible")

In this example:

  • If the given condition is true, i.e., the purchase amount is equal to or greater than 500, then the user qualifies for a discount. As a result, the code prints “Eligible”.
  • If the given condition is false, i.e., the purchase amount is less than 500, then the user does not qualify for a discount. As a result, the code prints “Ineligible”.

Now, let’s check the output:

Eligible

In the next section, we will discuss how we can use the ternary operator in our Python programs to simplify the conditional logic.

How to use Python ternary if statement

In Python, the ternary operator is a handy feature that enables us to write if-else statements in a single line of code. The syntax for the ternary operator is the following:

code_if_true if condition else code_if_false

In the syntax:

  • condition: The condition to be checked.
  • code_if_true: The code to be executed if the condition is true.
  • code_if_false: The code to be executed if the condition is false.

Next, let’s check out an example that uses the ternary operator to determine if a movie has sold 1000 tickets or more:

# Store the number of tickets sold in a variable
tickets = 1150
print("Equal or more") if (tickets >= 1000) else print("Less")

In this example:

  • If the given condition is true, i.e., the number of tickets sold is equal to or greater than 1000, then the code prints “Equal or more”.
  • If the given condition is false, i.e., the number of tickets sold is less than 1000, then the code prints “Less”.

Here is the output:

Equal or more

Besides the standard usage, we can use Python’s ternary operator in various other ways, such as nested ternary operators and ternary operators using dictionaries.

Let’s begin by learning how to use nested ternary operators in Python.

Nested ternary operators in Python

In Python, we can nest ternary operators within each other to handle multiple conditional statements in a single line. However, nesting too many ternary operators can make our code hard to read and maintain. So, we should only use it when absolutely necessary.

Here is an example that uses nested ternary operators to determine if a team has scored more than 3 goals in a football match:

# Store the number of goals scored in a variable
goals = 4
# Use nested ternary operators to check if the number of goals scored is more than 3
print("More") if (goals > 3) else (print("Less") if (goals < 3) else print("Equal"))

In this example:

  • The code first checks if the number of goals scored is more than 3. If true, it prints “More”.
  • If false, it checks if the number of goals scored is less than 3. If true, it prints “Less”.
  • If false, it means that the number of goals scored is equal to 3. So, it prints “Equal”.

Let’s check out the output:

More

Let’s explore other applications of the ternary operator, such as working with dictionaries.

Ternary operators using dictionaries in Python

In Python, dictionaries are a type of data structure that stores key-value pairs as its elements. This method can be particularly useful when we have multiple conditions to check.

Here is the syntax for implementing the ternary operator using a dictionary:

myDict = {True: value_if_true, False: value_if_false}[condition]

In the syntax:

  • myDict: The variable to be used for storing the dictionary with the given condition.
  • {True: value_if_true, False: value_if_false}: A dictionary containing two key-value pairs.
  • value_if_true: The value associated with the key True.
  • value_if_false: The value associated with the key False.
  • condition: The condition which will be checked and which the keys depend on.
    • If the condition is True, the value associated with the key True, i.e., value_if_true, is stored in myDict.
    • If the condition is False, the value associated with the key False, i.e., value_if_false, is stored in myDict.

Let’s look at an example that uses the ternary operator to set the value based on the condition of the key. This example checks if a batsman has scored 100 runs or more in a cricket match:

# Store the number of runs scored in a variable
runs = 126
res = {True: "Equal or more (Associated key: True)", False: "Less (Associated key: False)"}[runs >= 100]
# Print the result
print(res)

In this example:

  • If the given condition is true, i.e., the number of runs scored is greater than or equal to 100, then the value associated with the key True is stored in res.
  • If the given condition is false, i.e., the number of runs scored is less than 100, then the value associated with the key False is stored in res.

Here is the output:

Equal or more (Associated key: True)

In the next section, we will discuss some best practices that we should follow while using the ternary operator in Python.

Best practices for using Python ternary operator

When using the ternary operator in Python, it is important to follow some best practices to ensure efficient and clean code:

  • Keep it Simple: Try to use the ternary operator for simple conditions that can be easily understood at a glance.
  • Avoid Nesting: Limit the nesting of the ternary operator to avoid confusion and maintain readability.
  • Use Parentheses: Enclose the condition in parentheses to make the code clearer and prevent unexpected behavior.

Advantages and disadvantages of ternary operator

The advantages of utilizing the ternary operator in Python include:

  • Conciseness: The ternary operator allows us to write conditional statements in only a single line of code.
  • Readability: The ternary operator can make code easier to read by simplifying simple conditions.

However, the ternary operator has some disadvantages as well:

  • Limited Flexibility: The ternary operator may not be suitable for complex conditions that require multiple lines of code.
  • Debugging: Debugging code that uses ternary operators can be more challenging, as it can be harder to trace the flow of execution.

Conclusion

In this article, we have not only explored how to use the ternary operator in Python as an alternative to if-else statements but also learned how to implement nested ternary operators and ternary operators using dictionaries. By understanding its advantages and disadvantages and following the best practices while using it, we can write more efficient code. Remember to always consider the readability of your code when deciding whether to use if-else statements or the ternary operator.

If you want to learn more about conditional statements in Python, check out the Learn Python 3 course on Codecademy.

Author

Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team