web123456

[Skill Tree Co-construction] Python ternary expression

What is a ternary expression in Python

There is no tertiary expression (trigonomic operator) related to other languages ​​in Python, but there are similar syntaxes.
In Python, ternary expressions are a syntax structure, which are generally called by Python developers.Conditional expression, its structure is as follows:

expression(1)forTrueExecution statementifConditional expression (1) elseexpression(1)forFalseExecution statement

How to use it

For simplification of if statements

Tripartite expressions can make simpleif statementReduced to one line of code.

age = 20

cn = "adult" if age >= 18 else "Minor"
print(cn)

Originalif statementAs shown below:

age = 20
if age >= 18 :
    cn = "adult"
else:
    cn = "Minor"

Return multiple statements

You can write the following code structure to return multiple statements in a conditional expression.

age = 20

cn = "adult", "Greater than 18" if age >= 18 else "Minor"
print(cn)

The code returns a tuple with the content of('Adult', 'Greater than 18'), be sure not to use semicolons here;, otherwise only the result of the first statement is returned.

age = 20

cn = "adult"; "Greater than 18" if age >= 18 else "Minor"
print(cn)

After running the code, outputadult 。

Use ternary expressions inside a function

Some simple judgment logic can be simplified directly using ternary expressions, such as judging whether the incoming parameter is an even number.

def even_num(num):
    return True if num % 2 == 0 else False

Tripartite expressions are used for list comprehensions

In the list comprehension knowledge points, there are also application of ternary expressions, such as the following code.

li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# ret = [i for i in li if i % 2 == 0]
ret = [i if i % 2 == 0 else None for i in li]
print(ret)

The above code focuses on the code of the list generator and the location of the ternary expression.

Tripartite expressions and lambda

Sometimes ternary expressions can be combined with lambda to make the code more concise.

Declare a function and return a larger value

def max(a, b):
    if a > b:
        ret = a
    else:
        ret = b

    return ret

r = max(5, 6)
print(r)

Since the above code is very simple, you can directly implement it using the lambda anonymous function.

max = lambda a, b: a if a > b else b
r = max(10, 15)
print(r)

Improve the scene

Python conditional expressions can be used in nesting, but it is recommended to nest at most two layers, and when the code is simple, the specific encoding is as follows. You need to focus on learning the following questions.

When nesting, you also need to pay attention to the pairing problem of if and else.

# Write a ternary expression, first determine its value is greater than 20, and then determine it is an odd number (case, no practical meaning)
num = 19
ret = "less than 20" if num < 20 else ("odd number" if num % 2 == 1 else "even")
print(ret)

Extended knowledge

In many places, Python's conditional expressions will be expanded. The following two uses appear, but they are both of them that show off their skills and are not very practical.

For example, the following content:

Tuple conditional expression

age = 20

cn = ("Minor", "adult")[age >= 18]
print(cn)

The syntax format is as follows

 (Return when the following expression is false, return when the following expression is true)[Conditional expression]

Dictionary conditional expression

age = 20

cn = {False: "Minor", True: "adult"}[age >= 18]
print(cn)

You will find that there are some of the above two ways of writingDemonstrate mysterious, and the codeVery difficultRead, so it is not recommended to use it when encoding in actual combat.