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, with the help of examples.
Syntax of Ternary Operator
The syntax of Ternary Operator in Python is
[value_1] if [expression] else [value_2]
value_1 is selected if expression evaluates to True
. Or if the expression evaluates to False
, value_2 is selected.
You can either provide a value, variable, expression, or statement, for the value_1 and value_2.
Examples
In the following examples, we will see how to use Ternary Operator in selection one of the two values based on a condition, or executing one of the two statements based on a condition. We shall take a step further and look into nested Ternary Operator as well.
1. A simple example for Ternary Operator
In this example, we find out the maximum of given 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('Maximum :', max)
Output
Run the program. As a>b
returns False, b
is selected.
Maximum : 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.
2. Print statements in 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')
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.
3. Nested 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)
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.