Select Page

What is the Ternary Operator in Python?

by | Experience, Programming, Python, Tips

blog banner for post titled: What is the Ternary Operator in Python?

Conditional statements, such as if statements, direct the flow of programs by specifying particular blocks of code run only if a specific condition or set of conditions are met. We can test for a condition using the ternary operator. The ternary operator provides an elegant way to write conditional statements in a single line. The enhancement makes the code more compact and read.

This tutorial will go through conditional statements in Python and use the ternary operator.

Conditional Statements in Python

When writing a Python program, you may only want to execute certain code blocks when a specific condition is met. In such cases where you need conditional execution, conditional statements are helpful. Python supports the usual logical conditions from mathematics:

  • Equals: a == b
  • Not Equal: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

We can use these conditions most commonly in if statements and loops.

If Statement

The Python if statement evaluates whether a condition is equal to true or false. The statement will execute of code block if a specified condition is true. Else, that code block will not be executed. We can use an if… else statement to execute an alternate code block if the condition is not met. Let’s look at an example of an if… else statement to check whether a user is of age to drive.

age = 30

if age ≻= 18:

    print(f'You are old enough to learn to drive')

else:

    print(f'You are not old enough to drive yet')

Running this code returns:

You are old enough to learn to drive

The if statement checks whether the age variable is greater or equal to the most common legal age to drive, 18. If this condition is true, the first print statement is executed. Otherwise, the second print statement is executed. Let’s see what happens if we change the age to 15:

age = 15 

if age ≻= 18:

    print(f'You are old enough to learn to drive')

else:

    print(f'You are not old enough to drive yet')
You are not old enough to drive yet

The code returns a different output. The age is below the required amount, and so the else statement is executed instead of the if statement.

If statements take up at least two lines of code. We can write these statements more concisely using the Python ternary operator.

Python Ternary Operator

Python’s ternary operator evaluates something based on a true or false condition. We can think of ternary operators as one-line if-else statements.

The syntax of the Python ternary operator

[statement_1] if [expression] else [statement_2]

tells us we get statement_1 if the expression evaluates to True. Else if the expression evaluates to False, we get statement_2. As the name implies, the ternary operator needs three operands to run. The three operands are:

  • condition: Boolean expression that needs to evaluted as True or False.
  • val_true: A value to assign to the variable if the condtion evaluates to True.
  • val_false: A value to assign to the variable if the condition evaluates to True.

Putting the three operands together gives us:

some_var = val_true if [condition] else val_false

Where we assign either val_true or val_false to the variable some_var.

Replacing If-Else Statement with the Python Ternary Operator

Let’s look at a simple example of a Python program that uses the if-else statement method and the ternary operator. The program takes a distance input in years using the input() function.

distance = float(input('Enter the number of miles you ran today:  "))
if distance ≻= 26.2:

    marathon = "You ran a full marathon!"

else:

    marathon = "You have not completed a full marathon. You had: " + str(round(26.2 - distance, 1)) + " miles remaining"

print(f'Result: {marathon}')

The if-statement will assign the string “You ran a full marathon!” to the variable marathon if the distance entered is greater than or equal to 26.2 miles. Otherwise, the statement assigns,

“You have not completed a full marathon. You had: ” + str(round(26.2 – distance, 1)) + ” miles remaining” to marathon.

The rounded value in the last assignment is the distance left to complete to run a full marathon. Let’s run the code and see what happens:

Enter the number of miles you ran today: 23
Result: You have not completed a full marathon. You had: 3.2 miles remaining

We can use the ternary operator to make the program more concise.

distance = float(input('Enter the number of miles you ran today:  "))

marathon = "You ran a full marathon!" if distance ≻= 26.2 else "You have not completed a full marathon. You had: " + str(round(26.2 - distance, 1)) + " miles remaining"

In this statement, the left side of the assignment operator = is the variable marathon. The ternary operator evaluates the condition if distance ≻= 26.2. If the result is true, it returns val_true, which in this case is

“You ran a full marathon!”.

Otherwise, it returns val_false, which is:

“You have not completed a full marathon. You had: ” + str(round(26.2 – distance, 1)) + ” miles remaining”.

Let’s run the code to get the result:

Enter the number of miles you ran today: 23
Result: You have not completed a full marathon. You had: 3.2 miles remaining

Maximum of Two Numbers Using the Python Ternary Operator

a, b = 30, 50

max_val = a if a ≻ b else b

print(max_val)
50

Nested Python Ternary Operator

A ternary operator inside another ternary operator is called a nested ternary operator. You can nest multiple ternary operators in a single line of code. The syntax for the nested ternary operator is:

some_var = (val_true if [condition_2] else val_false) if [condition_1] else (val_true if [condition_3] else val_false)

Let’s break up this syntax into chunks to understand it:

  • First we evaluate if [condition_1]
  • Then whether we evaluate the left ternary operator statement or the right one depends on the boolean result from if [condition_1].
  • If condition_1 evaluates to True, then we evaluate the left one else we evaluate the right one.

Let’s look at an example of finding the largest of three numbers. First, we ask the user to input three integers:

print("Enter any three Numbers: ")

a = int(input())

b = int(input())

c = int(input())

Then we will use the nested ternary operator to find and print the largest of the three numbers.

largest = (a if a ≻ c else c) if a ≻ b else (b if b ≻ c else c)

print(f'The largest number out of the three is: {largest}')

This example tells us that:

  • We evaluate a ≻ b first
  • If a ≻ b is True then we evaluate the left statement, else we evaluate the right statement

Let’s run the code and give the program three numbers:

Enter any three Numbers: 

10

30

20

The largest number out of the three is: 30
  • The expression a > b is False because 10 is not greater than 30.
  • Therefore we evaluate the right ternary operator and the left one is skipped.
  • If b > c is true then b will be the result of the entire nested ternary statement.
  • In this example, b > c evaluates to true because 30 > 20.
  • Therefore b or 30 is the final result and is assigned to the variable largest.
  • The program prints the result to the console.

Python Ternary Operator with Tuples

Let’s look at how we can use the ternary operator with tuples. The syntax for the ternary operator is:

(if_check_is_false, if_check_is_true)[check]

With a numerical example, this looks like this:

a, b = 30, 50

max_val = (b,a) [a ≻ b]

print(max_val)
50

Python Ternary Operator with Dictionary

Let’s look at how we can use the ternary operator with the Dictionary data structure:

a, b = 30, 50
     
print({True: a, False: b} [a ≻ b]) 
40

In this case, if a > b is True, we get the True key’s value. Else if a > b is False, then we get the value of the False key.

Python Ternary Operator with the Lambda Function

The ternary operator with the Lambda function ensures we evaluate only one expression. In the cases of the Tuple or Dictionary, we evaluate both expressions.

a, b = 30, 50

max_val = (lambda: b, lambda: a) [a ≻ b]()

print(max_val)
50

Summary

The Python ternary operator is a concise way of implementing if-else statements. The operator values the given condition then returns a specific value depending on whether that condition is True or False. You can use nested ternary operators for cases where you have multiple conditions to evaluate. If the middle condition is true in the three conditions case, the Python interpreter evaluates the left condition, and otherwise, it evaluates the right condition. You can use the Python ternary operator with different data structures, including lambda functions, dictionaries, and tuples.

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!