×

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

Removing the First Character from the String in Python

String The string is the collection of characters. The strings in python are “immutable”; we cannot change a string once they are created. In python, whatever data we take as input...

4 minutes read.

Handling missing keys in Python dictionaries

In this lesson, you will discover how to create a Python application that will manage missing keys in a dictionary. Python dictionaries store data as key-value pairs, where each value...

3 minutes read.

Python bytearray()

Python bytearray() Class The bytearray() class is used to return a bytearray object which is an array of the specified bytes. It gives a mutable sequence of integers in the range 0...

1 minute read.

Python Built-in Functions

Python Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. The Python built- in functions are as follow: Methods Explaining abs() The abs() function returns...

6 minutes read.

Difference between Expression and Statement in Python

What is an expression in Python? Expression is a combination of operands and operators. Expression helps us to produce some other values. In the python programming language,  expressions produce some other value...

6 minutes read.

N2 in Python

N2 is known as Nearest Neighbor Algorithm, because it contains 2 N's (N-Nearest, N-Neighbor). This is a library in the python build using C++ and Python. Before N2 was made,...

3 minutes read.

To Do GUI Application using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Linear Regression using Sklearn with Example

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Python Namespace

In python, the namespace is a very important concept that should be understood before using any function or variables. When we write code, we often use variables, libraries, functions, modules, etc....

4 minutes read.

wxPython Panel class

wxPython Panel class The Widgets which is shown in the frame of GUI window such as text box, buttons, static text etc. are put inside the panel class of the wxpython...

2 minutes read.

Convert uppercase to lowercase in Python

Python String lower() By using the built-in string lower() method, all the uppercase characters can be converted into lowercase characters in a string, The lowercased string from the given string is returned...

1 minute read.

Python program to check if two strings are anagram or not

Python program to check if two strings are anagram or not Problem: This is a python program that takes two strings and checks if given strings are anagram or not. Examples: Input: string1...

1 minute read.

Tuple in Python

Tuples Tuples are the same as the list but as we know that lists are mutable means we can change the data from it. In the tuple we cannot change the...

6 minutes read.

Python Packages

A package is a collection of Python modules that share a similar namespace and are generated by putting all of the modules in a single directory with certain special files...

6 minutes read.

Import Module in Python

In this article, you will learn everything about “ Import ” in Python. Modules in python that are already created can be accessed and used in another code by importing the...

6 minutes read.

Excel to CSV in Python

Define MS Excel Microsoft Excel is an application provided by the Microsoft corporation which allows us to build graphs to build tables, and it is also used for the macro programming...

4 minutes read.

Magento 2 Site optimization

Magento 2 Site optimization Magento 2 is a CMS, commonly referred to as Intensive efficiency. Improving the speed and reliability of your Magento 2 app helps clients to achieve a better user experience while...

2 minutes read.

Python globals() function

Python globals() function The globals() function in Python returns the value of the named attribute of object where the ‘name’ must be a string. Syntax globals() Parameter NA Return This function returns the global symbol table as a dictionary. Example...

1 minute read.

Python set()

Python set() Class The set() class in Python returns a new set object, optionally with elements taken from iterable.  Syntax class set([iterable]) Parameter iterable : This parameter represents a sequence, collection or an iterator object Return This function returns a...

1 minute read.

Python String ljust() method

Python String ljust() method The string.ljust() method in Python will left align the string, where the padding is done using the parameter fillchar (space is default). Syntax String.ljust(width[, fillchar]) Parameter width: This parameter represents the...

2 minutes read.