How to use Ternary Operators in Python

A ternary operator is a simplified version of a conditional expression, which is written on one line.

 

Python Ternary Syntax

The first part of a ternary operation is the result. When the if statement is True, the result remains the same, otherwise the value in the else statement becomes the result.

 

result if expression else on_false_result

 

Python Ternary Example

Let's begin with a simple python ternary expression to see how it works in practice.

 

result = True if 2 == 1 else False
   
print(result)

 

In the above statement, we are evaluating if 2 is equal to 1, this can't be True so the result becomes False.

 

Ternary Nested if-else Statements

It is possible to check if two conditions are True using a ternary expression in Python like this:

 

x, y = 10, 5

result = True if x == y else True if x > y else False
   
print(result)
True

 

In the above example, we are checking if x is equal to y or x is greater than y.

Related Tutorials

 thumbnail

Python Print Formatting

September 24, 2020