Ternary operator

This article is participating in Python Theme Month,See the activity link for details

Ternary operators are commonly called conditional expressions in Python. These operators evaluate something based on whether the condition is true or not.

If else

format

1 if True else 2 #Copy the code

Example:

abc = True
state = 1 if abc else 2
print(state)
>>> 1
Copy the code

It allows quick testing of conditions rather than multi-line if statements. Many times it’s useful to keep your code compact but still maintainable.

Method 2 :(a,b)[True]

A more convenient and less widely used example involves tuples. Here is some sample code:

Format:

(is_false, is_true)[test] # test = True is_true, False is_falseCopy the code

Example:

nice = True
personality = ("mean", "nice")[nice]
print(personality)
>>> nice
Copy the code

This is easy because True == 1 and False == 0 can be done using lists in addition to tuples.

The example above is not widely used because it is easy to confuse tuples where to put true values and false values.

Another reason to avoid using a tuple triplet is that it causes two elements of the tuple to be evaluated, whereas the if-else triplet operator does not.

Example:

condition = True
print(2 if condition else 1/0)
>>> 2

print((1/0, 2)[condition])
>>> ZeroDivisionError: division by zero
Copy the code

This happens because using the tuple triplet technique, you first build the tuple and then find the index. For if-else ternary operators, it follows the normal if-else logical tree. Therefore, it is best to avoid using tuples if one case can throw an exception depending on the condition, or if either case is a computationally intensive approach.

Method three: shorthand three

There are also shorthand ternary tags in Python, which are shorter versions of the normal ternary operators you saw above.

example

>>> True or "Some"
True
>>>
>>> False or "Some"
'Some'
Copy the code

The first statement (True or “Some”) will return True, and the second statement (False or “Some”) will return Some.

This is helpful if you want to quickly examine the output of a function and give useful messages when the output is empty:

>>> output = None
>>> msg = output or "No data returned"
>>> print(msg)
No data returned
Copy the code

Or as an easy way to define function parameters with dynamic defaults:

>>> def my_function(real_name, optional_display_name=None):
>>>     optional_display_name = optional_display_name or real_name
>>>     print(optional_display_name)
>>> my_function("John")
John
>>> my_function("Mike", "anonymous123")
anonymous123
Copy the code