Assuming there are two numbers now, and we want to get the larger one, we can use an 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 similar to the ternary operator. In other programming languages, Python is a minimalist programming language. This new ternary operator uses the existing if else keyword to achieve the same functionality. The format of the ternary operator (conditional operator) using if else is as follows:
exp1 if condition else exp2
The condition is a judgment condition, and exp1 and exp2 are two expressions. If condition is true (the result is true), then exp1 is executed and the result of exp1 is used as the result of the entire expression; if condition is not (the result is false), then exp2 is executed and the result of exp2 is used as the result of the entire expression.
The previous statement max = a if a> b else b means:
Python ternary operators support nesting, which can make complex expressions. Pay attention to the pairing of “if and else” when nesting, for example:
a if a>b else c if c>d else d
Can be explained as:
a if a>b else ( c if c>d else d )
For example:
The program is a nested ternary operator. The program first evaluates a> b. If the expression is True, the program returns the first expression and print ("a bigger than b"), otherwise it will continue to execute the content after the else, that is:
(print ("a less than b") if a < b else print ("a equal to b"))
After entering the expression, first determine whether a < b is true. If the result of a < b is True, print ("a less than b") will be executed, otherwise print ("a equal to b") will be executed.
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises