This is the question that comes to mind when reviewing lambda expressions today, and it is well known that the ternary operator (?:) in C-Series languages is a very useful statement,
About the ternary operator in C
Expression 1? Expression 2: Expression 3
So what should be done in Python, see the following example:
The answer is: X = (expression 1) and Expression 2 (truth return) or expression 3 (false value returned)
As an example:
Copy the Code code as follows:
def main ():
y = 5
x = (Y > 5) and 2 or 4
Print X
Pass
This code is the meaning of the output is 4, you can change the condition of the expression (y<=5) This time the output is 2
Why you can get the result:
0, ', [], (), {}, none are false in a Boolean context, and everything else is true.
In Python, and and OR, the Boolean logic calculus is executed, but they do not return a Boolean value; instead, they return one of the values that they actually compare.
If all values in the Boolean context are true, then and returns the last value. If a value in the context is false, then and returns the first false value.
If a value is true, or returns the value immediately. If all values are false, or returns the last False value
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 the expression 2 or 3 is a few defined false values (0, ", [], (), {}, None), it will affect the judgment, my suggestion is that the false values are in the form of a string, and will" "special processing as" ". Follow up and make judgments
See again the power of Python if you have any insights to welcome comments.
Postscript:
Having read some articles recently, a great God has given the problem a perfect solution to this flaw.
x= (expression 1) and[expression 2 (true return)]or[expression 3 (False value return)] (note: expression 2 and expression 3 cannot be 0, ', [], (), {}, None)
The 2,3 of the expression is enclosed in brackets so that the values of the two will never be false, which is a good solution.