Python Ternary operator

Python Ternary operator

Python Ternary operator is used to select one of the two values based on a condition. It is a miniature of if-else statement that assigns one of the two values to a variable.

In this tutorial, we will learn how to use Ternary Operator in Python.

The syntax of Python Ternary Operator is:

[statement_1] if [expression] else [statement_2]

statement_1 is selected if expression evaluates to True. Else if the expression evaluates to False, statement_2 is selected.

You can either provide a value, variable or statement for the statement_1 and statement_2.

Example 1: Python Ternary Operator

In this example, we will find out the maximum of two numbers, using ternary operator.

The ternary operator in the following program selects a or b based on the condition a>b evaluating to True or False respectively.

Python Program

a, b = 2, 5

#get maximum of a, b
max = a if a > b else b 
  
print(max) 
Run this program

Output

Run the program. As a>b returns False, b is selected.

5

You may swap the values of a and b, and run the program. The condition would evaluate to True and a would be selected.

Example 2: Print Statements in Python Ternary Operator

In this example, we will write print statements in the ternary operator. Based on the return value of condition, Python executes one of the print statements.

Python Program

a, b = 2, 5

#ternary operator
print('Python') if a > b else print('Examples') 
Run this program

Output

Run the program. As a>b returns False, second print statement is executed.

Examples

This example demonstrates that you can run any Python function inside a Ternary Operator.

Example 1: Nested Python Ternary Operator

You can nest a ternary operator in another statement with ternary operator.

In the following example, we shall use nested ternary operator and find the maximum of three numbers.

Python Program

a, b, c = 15, 93, 22

#nested ternary operator
max = a if a > b and a>c else b if b>c else c

print(max)
Run this program

After the first else keyword, that is another ternary operator.

Output

93

Change the values for a, b and c, and try running the nested ternary operator.

Summary

In this tutorial of Python Examples, we learned what Ternary Operator is in Python, how to use it in programs in different scenarios like basic example; executing statements inside Ternary Operator; nested Ternary Operator; etc., with the help of well detailed Python programs.