Detailed usage of Python ternary operator (ternary operator)

We start this section with a concrete example. 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

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 the already existing if else keyword to achieve the same functionality.

The format of using if else to implement the ternary operator (conditional operator) is as follows:

exp1 if contion else exp2

condition is the judgment condition, and exp1 and exp2 are two expressions. If the condition is true (result is true), execute exp1, and use the result of exp1 as the result of the entire expression; if the condition is not true (result is false), execute exp2, and use the result of exp2 as the result of the entire expression.

The meaning of the previous statement max = a if a>b else bis:

  • 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.

Nesting of ternary operators

Python ternary operators support nesting, so that more complex expressions can be formed. When nesting, you need to pay attention to the pairing of if and else, 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 )

[Example] Use the Python ternary operator to judge the relationship between two numbers:

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") )

Possible run results:

Input a: 45↙
Input b: 100↙
a is less than b

The program is a nested ternary operator. The program first evaluates a>b. 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") )

Guess you like

Origin blog.csdn.net/qq_34274756/article/details/131353495