Ternary Operator in Python with Example

Python 2.5 introduced a shorthand operator, known as ternary operator. This operator requires three operands and performs conditional test based on a condition being true or false.

Python supports only one ternary operator. It is also known as conditional expression in Python, that allows us to write a simple conditional statement in a single line.

We often use this conditional expression as a shorthand notation for multiline if-else statement.

It makes the code much more simple, shorter and readable. It performs the same task as multiline if-else statement.

Syntax for Python Ternary Operator


A basic syntax for using the ternary operator in Python language is as:

true_value if conditional_expression else false_value
Or,
variable = true_value if conditional_expression else false_value

In the above syntax, the conditional_expression is a boolean expression that produces a boolean value (either true or false). Python interpreter first evaluates conditonal_expression.

If the conditonal_expression evaluates true, the operator outputs the true_value. If the conditional_expression evaluates false, it outputs false_value.

The ternary operator evaluates only one of the two subexpression true_value and false_value depending on the truth value of the conditional expression.


Note: Unlike the other programming languages, such as C++ or Java, Python does not have (?:) ternary operator but has a “conditional expression” that performs the similar task as if-else statement.

Python Conditional Expression Examples


Let’s understand the concept of ternary operator or conditional expression with the help of some unique examples.

Example 1:

Consider the following statement below:

msg = 'Hello' if x > y else 'Goodbye'

If “x” is greater than “y”, the value of variable msg will be “Hello” otherwise the value of variable msg will be “Goodbye”.

In other words, if “x” is greater than “y”, ‘Hello’ is assigned to the variable msg, else “Goodbye” is assigned to the variable msg. Look at the below figure to understand more clearly.

An example of ternary operator in Python

An if-else statement instead of the above conditional expression is as follows:

if(x > y):
    msg = 'Hello'
else:
    msg = 'Goodbye'

Example 2:

Consider another the code below:

print('Hello' if True else 'Goodbye') # Output: Hello
print('Hello' if False else 'Goodbye') # Output: Goodbye

Example 3:

variable = expression1 if conditional_expression else expression2

This statement states that if the conditional_expression returns true, expression1 gets executed, else the expression2 gets executed and the final outcome stored in a variable.

Example 4:

print("Passed" if (studentGrade >= 40) else “Failed”)

This statement contains a test expression that evaluates to the string “Passed” if the condition (studentGrade >= 40) is true. If the test expression (studentGrade >= 40) is false, it evaluates the string “Failed”.

Python Conditional (Ternary) Operator Example Program


Example 1: Let’s create a Python program in which we will determine the greatest number between two numbers using ternary operator.

x, y = 20, 40
z = 20 if (x > y) else 40
print("Greatest number: ", z)
Output:
      Greatest number:  40

In the preceding example, we have assigned the values 20 and 40 to the variables x and y, respectively. The conditional variable z stores the value returned by the conditional expression.

In the conditional expression, the value of x is not greater than y, the operator assigns the value after the else keyword to the variable z. If the value of x becomes greater than y, the operator assigns the value before the if keyword to the variable z.


Example 2: Let’s write the code to find the greatest of the three numbers entered by the user using a ternary operator.

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
greatest_num = (num1 if (num1 > num3) else num3) if (num1 > num2) else (num2 if (num2 > num3) else num3)
print('The greatest number among three numbers: ', str(greatest_num))
Output:
      Enter the first number: 30
      Enter the second number: 10
      Enter the third number: 40
      The greatest number among three numbers: 40

Example 3: Let’s create a Python program to check that a person is eligible to vote or not.

age = int(input("How old are you?"))
eligible = "You are eligible to vote." if (age >= 18) else "You are not eligible to vote."
print(eligible)
Output:
      How old are you? 19
      You are eligible to vote.

When you will execute this program, it will prompt to you to enter your age. The age that you will enter will store in the variable age.

For example, we have entered the age 19. This value is assigned to the variable age in the program. Since the entered value 19 is greater than the eligible age 18, the string value to the left of the if keyword is assigned to the variable eligible. A message “You are eligible to vote” prints on the console.


Example 4: Let’s create a Python program using ternary operator to check whether a year is a leap year or not.

total = 0;
yearCheck = int(input("Enter a year: "))

check4 = 1 if (yearCheck % 4 == 0) else 0
check100 = -1 if (yearCheck % 100 == 0) else 0
check400 = 1 if (yearCheck % 400 == 0) else 0

total = check4 + check100 + check400
print("Leap year" if(total == 1) else "Not leap year")
Output:
      Enter a year: 2024
      Leap year
      Enter a year: 2023
      Not leap year

In the above code, we have used the following algorithm to check leap year. They are as:

1. If the entered year is divisible by 4, add 1.
2. If the entered year is divisible by 100, subtract 1.
3. If the entered year is divisible by 400, add 1.
4. If the total is 1, the year is a leap year, otherwise not a leap year.

The general rule to check a leap year is that if a year is divisible by 4, and it is not divisible by 100, unless it is also divisible by 400.

For example, the years 1800 and 2200 are divisible by 100, but not divisible by 400. Therefore, they are not leap year. However, the year 2024 is a leap year.


Example 5: Let’s write a Python program in which we will use the print function in ternary operator.

# Python program to find the greater number between two numbers.
num1 = int(input('Enter your first number: '))
num2 = int(input('Enter your second number: '))
print(num1, "is greater number") if (num1 > num2) else print(num2, "is greater number")
Output:
      Enter your first number: 20
      Enter your second number: 50
      50 is greater number

Nested Ternary Operator Example


Let’s take an example program in which we will make nested ternary operator to replace nested if-else statements.

num1, num2 = 10, 20
# Nested ternary operator.
num = "num1 = num2" if(num1 == num2) else "num1 > num2" if(num1 > num2) else "num2 > num1"
print(num)
Output:
      num2 > num1

We can write the above program using nested if-else statement in multiple lines of code like this:

num1, num2 = 10, 20
# Nested if-else statement.
if num1 != num2:
    if num1 > num2:
        print("num1 > num2")
    else:
        print("num2 > num1")
else:
    print("num1 = num2")
Output:
      num2 > num1

In this tutorial, we have learned about conditional expression or ternary operator in Python with examples. Hope that you will have understood the basic points of ternary operator and practiced all example programs.
Thanks for reading!!!
Next ⇒ What is Expression in Python⇐ Prev Next ⇒