This is the problem that comes to mind when you review lambda expressions today, and it is well known that the ternary operator (?:) in the C-series language is a very useful statement,
About ternary operators in C
Expression of 1? Expression 2: Expression 3
So how do you do it in Python, see the following example:
The answer is: X = (expression 1) and Expression 2 (truth-return) or expression 3 (false value return)
As an example:
Copy Code code as follows:
def main ():
y = 5
x = (Y > 5) and 2 or 4
Print X
Pass
The output of this code is 4, the condition of the expression can be changed to (y<=5) and the output is 2.
Why can I get this result:
0, ', [], (), {}, none is false in the Boolean context; everything else is true.
In Python, and and or perform boolean logical calculations, but they do not return Boolean values; instead, they return one of the values that they actually compare.
If all values in the Boolean context are true, then and the last value is returned. If a value in the context is false, then and the first false value is returned.
If a value is true, or immediately returns the value. If all of the values are false, or the last false value is returned
Based on the above background, you should still be able to understand the meaning of this expression.
"Note:" There should be some flaws in this usage, if Expression 2 or 3 is a few defined false values (0, ' ", [], (), {}, None), it's going to affect the judgment, my advice. These false values are expressed as strings, and special processing is" ". Follow up and make judgments
Once again to see how powerful Python is, if you have any insights to welcome comments.
Postscript:
Recently read some articles, a big God to this problem to this flaw to give a perfect solution
x= (expression 1) and[expression 2 (Truth return)]or[expression 3 (False value return)] (note: expression 2 and expression 3 cannot be 0, ', [], (), {}, None)
The expression 2,3 is enclosed in brackets so that the value of both will never be false, and the solution is good indeed.