Python and, or and-or syntax summary, pythonand-or
I. and:
In Python, and or execute boolean logic calculus, as you expected, but they do not return boolean values; instead, they return one of the values actually compared.
Copy codeThe Code is as follows:
>>> 'A' and 'B' B '>>>'' and' B '> 'A' and' B 'and 'C' c'
Calculates the value of the expression from left to right in a Boolean context. If all values in the Boolean context are true, and returns the last value.
If a value in the Boolean context is false, and returns the first false value
Ii. or:
Copy codeThe Code is as follows:
>>> 'A' or 'B' a' >>>'' or 'B' B '> ''or [] or {}
{}>>> 0 or 'A' or 'C''
[Code]
When using or, the values are calculated from left to right in a Boolean context, just like and. If one value is true, or immediately returns this value
If all values are false, or returns the last value.
Note: or in a Boolean context, the expression is calculated until the first true value is found, and the remaining comparison values are ignored.
3. and-or:
And-or combines the preceding two syntaxes for reasoning.
[Code]
>>> A = 'first '>>> B = 'second' >>> 1 and a or B' first >>> (1 and) or B 'first >>> 0 and a or B' second' >>> (0 and a) or B 'second' >>>
This syntax looks similar to bool in C? A: expression B. The entire expression is calculated from left to right, so the and expression is first calculated. The value of 1 and 'first' is 'first ', and the value of 'first' or 'second' is 'first '.
The value of 0 and 'first' is False, and the value of 0 or 'second' is 'second '.
And-or is mainly used to imitate the Three-object operator bool? A: B, that is, if the expression bool is true, a is used; otherwise, B is used.
And-or technique, bool and a or B expression. When a's value in Boolean context is false, it won't be like the C expression bool? A: B works that way.
4. Secure use and-or
Copy codeThe Code is as follows:
>>> A = "" >>> B = "second" >>> (1 and [a] or [B])
[''] >>> (1 and [a] or [B]) [0]'' >>>
Because [a] is a non-empty list, it will never be false. Even if a is 0, '', or other dummy values, the list [a] is true because it has an element.
A responsible programmer should encapsulate the and-or technique into a function:
Copy codeThe Code is as follows:
Def choose (bool, a, B): return (bool and [a] or [B]) [0] print choose (1, '', 'second ')#''