 # Ternary Operator in Python

## Ternary Operator in Python

Ternary operators are also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5.
It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.
Syntax :

`[on_true] if [expression] else [on_false]`
• Simple Method to use ternary operator:
 `# Program to demonstrate conditional operator` `a, b ``=` `10``, ``20` `# Copy value of a in min if a < b else copy b` `min` `=` `a ``if` `a < b ``else` `b` `print``(``min``)`

Output:

`10`
• Direct Method by using tuples, Dictionary, and lambda
 `# Python program to demonstrate ternary operator` `a, b ``=` `10``, ``20` `# Use tuple for selecting an item` `# (if_test_false,if_test_true)[test]` `# if [a

Output:

```10
10
10```
• Ternary operator can be written as nested if-else:
 `# Python program to demonstrate nested ternary operator` `a, b ``=` `10``, ``20` `print` `(``"Both a and b are equal"` `if` `a ``=``=` `b ``else` `"a is greater than b"` `        ``if` `a > b ``else` `"b is greater than a"``)`

The above approach can be written as:

 `# Python program to demonstrate nested ternary operator` `a, b ``=` `10``, ``20` `if` `a !``=` `b:` `    ``if` `a > b:` `        ``print``(``"a is greater than b"``)` `    ``else``:` `        ``print``(``"b is greater than a"``)` `else``:` `    ``print``(``"Both a and b are equal"``)`

Output:

` b is greater than a`

### Important Points:

• First the given condition is evaluated (a < b), then either a or b is returned based on the Boolean value returned by the condition
• Order of the arguments in the operator is different from other languages like C/C++ .
• Conditional expressions have the lowest priority amongst all Python operations.

Method used prior to 2.5 when the ternary operator was not present
In an expression like the one given below, the interpreter checks for the expression if this is true then on_true is evaluated, else the on_false is evaluated.
Syntax :

```'''When condition becomes true, expression [on_false]
is not executed and value of "True and [on_true]"
is returned.  Else value of "False or [on_false]"
is returned.
Note that "True and x" is equal to x.
And "False or x" is equal to x. '''
[expression] and [on_true] or [on_false]```

Example :

 `# Program to demonstrate conditional operator` `a, b ``=` `10``, ``20` `# If a is less than b, then a is assigned` `# else b is assigned (Note : it doesn't` `# work if a is 0.` `min` `=` `a < b ``and` `a ``or` `b` `print``(``min``)`

Output:

`10`

Note : The only drawback of this method is that on_true must not be zero or False. If this happens on_false will be evaluated always. The reason for that is if the expression is true, the interpreter will check for the on_true, if that will be zero or false, that will force the interpreter to check for on_false to give the final result of the whole expression.

Last Updated on October 24, 2021 by admin

## Django CRUD (Create, Retrieve, Update, Delete) Function Based ViewsDjango CRUD (Create, Retrieve, Update, Delete) Function Based Views

Django CRUD (Create, Retrieve, Update, Delete) Function Based Views Django is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks. Django

## Python – os.path.split() methodPython – os.path.split() method

Python | os.path.split() method OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is submodule of OS module in Python used

## Python – Extract specific keys from dictionaryPython – Extract specific keys from dictionary

Python | Extract specific keys from dictionary We have a lot of variations and applications of dictionary container in Python and sometimes, we wish to perform a filter of keys in dictionary, i.e extracting just the keys which are present

## Ways to import CSV files in Google ColabWays to import CSV files in Google Colab

Ways to import CSV files in Google Colab Colab (short for Colaboratory) is Google’s free platform which enables users to code in Python. It is a Jupyter Notebook-based cloud service, provided by Google. This platform allows us to train the Machine

## Create Table Using TkinterCreate Table Using Tkinter

Create Table Using Tkinter Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python.

## string.punctuation in Pythonstring.punctuation in Python

string.punctuation in Python In Python3, string.punctuation is a pre-initialized string used as string constant. In Python, string.punctuation will give the all sets of punctuation. Syntax : string.punctuation Parameters : Doesn’t take any parameter, since it’s not a function. Returns : Return all sets of punctuation. Note : Make

## Multi-dimensional lists in PythonMulti-dimensional lists in Python

Multi-dimensional lists in Python There can be more than one additional dimension to lists in Python. Keeping in mind that a list can hold other lists, that basic principle can be applied over and over. Multi-dimensional lists are the lists within

## Python – Creating a dictionary of ListsPython – Creating a dictionary of Lists

In this article, we will see different ways of creating a dictionary of list. Note that the restriction with keys in Python dictionary is only immutable data types can be used as keys, which means we cannot use a dictionary