×

Ternary operators in python

Starting from Python version 2.5, ternary operators are also known as Conditional operators. Using these operators, we can evaluate any problem based on a condition. It is an alternative and sophisticated form of the if-else statements. Rather than using if-else statements that take multiple lines, we can check if a particular condition is true or false and evaluate based on the condition in a single line using these operators.

Syntax:

[code_if_true] if [condition] else [code_if_false]

Here,

  • code_if_true: If the expression in the if [condition] is true, this code will be executed.
  • condition: Expression based on which the code will be executed.
  • code_if_false: If the expression in the if [condition] is false, this code will be executed.

Example:

Let us write a program to check the minimum number in the given two numbers:

a = int (input ("Enter the first number: "))
b = int (input ("Enter the second number: "))
min = a if (a < b) else b
print ("The minimum number in a and b is: ", min)

Output:

Enter the first number: 7
Enter the second number: 89
The minimum number in a and b is: 7
  • Printing directly using Ternary Operator

We can place a print statement in the place of expression to be printed if the condition is true or false. This way, we can further decrease the length of the program as we need not to write another line for printing the result.

a = int (input ("Enter the first number: "))
b = int (input ("Enter the second number: "))
print (a, "is smaller") if (a < b) else print (b, "is smaller")

Output:

Enter the first number: 4
Enter the second number: 3
3 is smaller
  • Using Tuples, dictionary, and lambda, we can simplify it. Let us take a simple example:
a = int (input ("Enter the first number: "))
b = int (input ("Enter the second number: "))


min1 = (b, a) [a < b]
print("Minimum value by using tuples: ", min1)


min2 = {True: a, False: b} [a < b]
print ("Minimum value by using a dictionary: ", min2)


min3 = (lambda: b, lambda: a) [a < b] ()
print ("Minimum value by using lambda: ", min3)

Output:

Enter the first number: 5
Enter the second number: 9
Minimum value by using tuples:  5
Minimum value by using a dictionary:  5
Minimum value by using lambda:  5

Understanding:

  • Tuples:

In the line:

min1 = (b, a) [a < b]

The two possible outputs for true and false conditions must be placed in a tuple in the order: (False, True), and the condition to check is placed after the tuple in square braces.

We gave the input

a = 5

b = 9

The condition a is less than b is true; hence, the second value in the tuple is printed.

  • Dictionary:

In the line:

min2 = {True: a, False : b} [a < b]

Dictionary is a collection of keys with corresponding values. Hence, we placed the possible outcomes of true and false conditions as values to True and False keys. Hence, when the condition becomes true, the value of the True key will be executed, and when the condition is false, the value of the False key will be executed. The condition to be checked should be written next.

We gave the input

a = 5

b = 9

The condition a is less than b is true; hence, the True key value: "a," which is equal to 5, is printed.

  • Lambda function:

This method is more efficient than tuples and dictionaries because, here, we can be assured that only one expression will be executed.

In the line:

min3 = (lambda: b, lambda: a) [a < b] ()

We used two lambda functions with no arguments. Hence, according to the result of the expression, if a is less than b is true, then the second lambda function is executed; else, the first value will be printed. The condition is placed next.

We gave the input

a = 5

b = 9

The condition a is less than b is true; hence, the second lambda function is executed, and the value of a is printed.

Nested if-else:

We can write nested if-else statements in this format. Generally, writing nested if-else statements takes multiple lines, but using this format, we can make it in less number of lines.

Let us first take the normal nested if-else statement program to see the difference:

a = int (input ("Enter the first number: "))
b = int (input ("Enter the second number: "))
if a == b:
    print ("a and b are equal==",a)
else:
    if a > b:
        print (a, " is greater than ", b)
    else:
        print (b, " is greater than", a)

Output:

Enter the first number: 4
Enter the second number: 4
a and b are equal== 4
  • As you can observe in the above program, writing nested if-else took 7 lines. The same code in ternary form can be written in 2 lines:
a = int (input ("Enter the first number: "))
b = int (input ("Enter the second number: "))
print ("Equal" if a == b else (a, "is greater") if a > b else (b, "is greater"))

Output:

Enter the first number: 4
Enter the second number: 4
Equal

Understanding:

We need to place an if-else statement inside another if statement. Instead of using the traditional nested if-else statements, we used the ternary form.  It took 1 line making the program simpler.

  • Python Ternary operators are different from programming languages like C and C++.
  • Ternary operators have the lowest priority in the operators’ hierarchy.

Short-hand Ternary:

Python also provides us with a way to make the code even smaller. This operator is the more shrunk version of the normal ternary operators.

Ternary Operators in Python

This method is useful when we need to quickly check the output of a function and display a message if the output is empty.

>>> Output = None
>>> Message = Output or "Output is empty"
>>> print (Message)
Output is empty

Related Topics

Python Program to Print Sum of all Elements in an Array

Python program to print sum of all elements in an array A set of objects stored in contiguous memory locations is referred to as an array. The concept is to keep...

2 minutes read.

How to change the names of Columns in Python

Introduction To play with huge amounts of data, in Python we require a tool. The tool which is available in Python is Pandas. Pandas is an open-source library. It is used...

3 minutes read.

Python List copy() method

Python List copy () method The list.copy () method returns a shallow copy of the list. Syntax list.copy() Parameter NA Return This function returns the copy for the given list. Example 1 # Python program explaining # the list.copy() method # passing the...

1 minute read.

Problem-solving with algorithm and data structures using Python

What is problem-solving? There is no universal method for solving problems. It's frequently a special process that balances your immediate and long-term goals with your available resources. However, several models emphasise...

3 minutes read.

Iterate a Dictionary in Python – Part 2

In this tutorial, we will learn above various methods used to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to...

3 minutes read.

Sentiment Analysis using NLTK

Introduction Data is being produced at an astounding rate and volume in the field of the internet and other digital services nowadays. Researchers, engineers, and data analysts often work with tabular...

7 minutes read.

Python Project Ideas for Beginners

Python project ideas for beginners Advanced Python is an amazing platform to grow and achieve success as a developer in the future. Python is a programming language that can be very...

7 minutes read.

Checking whether a String Contains a Set of Characters in python

In this tutorial, we will learn how to examine or check whether a string contains any set of characters or a substring and if it contains, we will learn how...

6 minutes read.

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy....

5 minutes read.

Python SymPy

A Python package for symbolic mathematics is called SymPy. Its goal is to develop into a fully-fledged computer algebra system (CAS) while maintaining the code as straightforward as possible to...

3 minutes read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

Python Operators

Operators in Python programming An operator is a symbol that operates on one or more operands. An operand is a value or a variable on which we perform the operation....

5 minutes read.

API Requests using Python

What is an API? API stands for Application Programming Interface. It is commonly known as API. It provides an environment that helps two or more computer programs to contact each other....

5 minutes read.

Salary of Python Developers in India

In this tutorial, we will understand who python developers are and what is their salary when they work in India. Python Developers Python Developers are the people who are involved in designing...

4 minutes read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Front end in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

4 minutes read.

Arithmetic Expressions in Python

What is Python Expression? Expressions are collections of operands and operators. Python expressions are translated by the Python interpreter into some value or outcome. In Python, an expression is made up...

13 minutes read.

Python Basics

In this tutorial, we will learn about the basics of Python, a very famous programming language. This tutorial will help you understand the language better if you start with python....

8 minutes read.

How to run a Program in Python

How to run a Program in Python Writing a program in Python is an easy task, beginners who are ready to kickstart their career in the world of programming can create...

3 minutes read.

Python ltrim() function

Python ltrim() function The ltrim() function in PHP removes whitespace or other predefined characters from the beginning or left side of a string. The related functions are as follows: rtrim() – This function is used to...

1 minute read.