Detailed usage of Python ternary operator (ternary operator) (including Python code)

I. Introduction

The ternary operator, also known as the conditional operator, is an important part of computer languages ​​(c, c++, java, etc.). It is the only operator with 3 operands, sometimes called the ternary operator.

definition:

For the conditional expression b ? x : y, the condition b is calculated first, and then judged. If the value of b is true, calculate the value of x, and the operation result is the value of x; otherwise, calculate the value of y, and the operation result is the value of y.

A conditional expression never evaluates to both x and y.

Conditional operators are right-associative, that is, grouped and evaluated from right to left. For example, a ? b : c ? d : ea ? b : (c ? d : e) will be executed.

Can be understood as a condition? Result 1 : in result 2? The numbers are format requirements. It can also be understood as whether the condition is true, the condition is true as result 1, otherwise it is result 2.

Note: In C language, the types of result 1 and result 2 must be consistent.

a ? b : c is simply understood as:

if(a) {
    
    
    return b;
    
} else {
    
     
    return c;
}

An example in C language explains:

int a = 2;
 
int c = 3;
 
int b = (a > c) ? a : c;
 
cout << "b:" << b << endl;

coutis the output symbol of the C++ language.

endlEnglish means end of line, that is, the output of one line ends, and then the next line is output.

cout<<endlis to end the output of this line of the program.

cout<<"b:"<<b<<endl: Similar to C: printf("b:%d\n",b).

We know a>cthe result is False, so the b value returns c.

So our output is:

b:3

Let's look at a complex one:

int a = 1, b = 2, z, c = 3;
z = a > b ? a : (b > c ? b : c);
cout << "z:" << z << endl;

Let's look at the right part: b>cthe return value is False, so return3

a>breturns False, so the final output is:z:3

So far, everyone understands the definition of the ternary operator.

Second, the ternary operator in Python

The Python language does not have such a ternary operation like Java, JavaScript, etc.:

The condition of the judgment? The result when the condition is true: the result when the condition is false

But Python also has its own ternary operator:

The result when the condition is true The condition of the if clause else The result when the condition is false

That is: Python can ifrealize the function of the ternary operator through the statement, so this kind of ifstatement can be regarded as the ternary operator. The specific syntax format is as follows:

Return True to execute if expression else return False to execute

Let's give a simple example to help understand:

Suppose there are two numbers now and we want to get the larger one, then we can use if else statement, for example:

if a>b:
    max = a
else:
    max = b

But Python provides a more concise way of writing, as follows:

max = a if a>b else b

Here is a detailed explanation:

max = a if a>b else bThe meaning of is:

If a>b is established, take a as the value of the entire expression and assign it to the variable max;

If a > b is not true, take b as the value of the entire expression and assign it to the variable max.

Second example:

a = "返回True执行" if 3 > 4 else "返回False执行"
print (a) 

Our judgment condition 3>4is not satisfied, so execute返回False执行

operation result:返回False执行

3. Place multiple statements in the ternary operator

In Python's ternary operator, it is allowed to place multiple statements in "return True execution" and "return False execution", there are two ways:

1. Separated by commas, each placed statement will be executed, and the program returns a tuple consisting of the return values ​​of multiple statements:

b = 3 + 1, "3 > 2",print('AAA') if 1 > 2 else print("BBB"),2 + 2
print (b)

In the above example, because 1 > 2is , the four statements are Falseexecuted and returned . Since the print() function has no return value, it returns None. The running results are as follows:3 + 1,"3 > 2",2 + 2,print("BBB")

BBB
(4, '3 > 2', None, 4)

2. Use English semicolons to separate, each statement will be executed, but the program will only return the return value of the first statement:

b = 1 + 1; "3 > 2";print('AAA') if 1 > 2 else print("BBB");2 + 2
print (b)

The if...else... here executes print("BBB"), which returns the return value 2 of the first statement 1 + 1, so the running results are as follows:

BBB
2

Four. Summary

This is a way of writing similar to the ternary operator in other programming languages ? :.

Python, being a minimalist programming language, does not introduce ? :this new operator, but uses existing if elsekeywords to achieve the same functionality.

if elseThe format for implementing the ternary operator (conditional operator) using is as follows:

exp1 if contion else exp2

conditionis the judgment condition, exp1and exp2are two expressions.

If the condition is true (the result is true), execute exp1, and use the result of exp1 as the result of the entire expression;

If the condition is not true (the result is false), execute exp2, and use the result of exp2 as the result of the entire expression.

5. Nesting of ternary operators

Python ternary operators support nesting, so that more complex expressions can be formed. When nesting, you need to pay attention if 和 elseto the pairing of , for example:

a if a>b else c if c>d else d

should be understood as:

a if a>b else ( c if c>d else d )

It is what we said above: the conditional operator is right associative

example:

a = int( input("Input a: ") )
b = int( input("Input b: ") )
print("a大于b") if a>b else ( print("a小于b") if a<b else print("a等于b") )

operation result:

Input a: 5
Input b: 6
a小于b

The program is a nested ternary operator. The program a>bevaluates , if the expression is True, the program will return to execute the first expression print("a is greater than b"), otherwise it will continue to execute the content after else, that is: ( print("a小于b") if a<b else print("a等于b") ), after entering the expression, First judge whether a<b is true, if the result of a<b is True, print("a is less than b") will be executed, otherwise print("a is equal to b") will be executed.

Guess you like

Origin blog.csdn.net/wzk4869/article/details/126550962