Python Logical Operators
Solution 1:
The operator and returns the last element if no element is False
(or an equivalent value, such as 0
).
For example,
>>> 1and44# Given that 4 is the last element>>> Falseand4False# Given that there is a False element>>> 1and2and33# 3 is the last element and there are no False elements>>> 0and4False# Given that 0 is interpreted as a False element
The operator or returns the first element that is not False
. If there are no such value, it returns False
.
For example,
>>> 1or21# Given that 1 is the first element that is not False>>> 0or22# Given that 2 is the first element not False/0>>> 0orFalseorNoneor1010# 0 and None are also treated as False>>> 0orFalseFalse# When all elements are False or equivalent
Solution 2:
This can be confusing - you're not the first to be tripped up by it.
Python considers 0 (zero), False, None or empty values (like [] or '') as false, and anything else as true.
The "and" and "or" operators return one of the operands according to these rules:
- "x and y" means: if x is false then x, else y
- "x or y" means: if x is false then y, else x
The page you reference doesn't explain this as clearly as it could, but their examples are correct.
Solution 3:
I don't know if this helps, but to extend @JCOC611's answer, I think of it as returning the first element that determines the value of the logical statement. So, for a string of 'and's, the first False value or the last True value (if all values are True) determine the ultimate result. Similarly, for a string of 'or's, the first True value or last False value (if all values are False) determine the ultimate result.
>>> 1or4and21#First element of main or that is True>>> (1or4) and22#Last element of main and that is True>>> 1or0and21>>> (0or0) and20>>> (0or7) andFalseFalse#Since (0 or 7) is True, the final False determines the value of this statement >>> (Falseor7) and00#Since (False or 7) is True, the final 0(i.e. False) determines the value of this statement)
The first line is read as 1 or (4 and 2), so since 1 makes the ultimate statement True, its value is returned. The second line is governed by the 'and' statement, so the final 2 is the value returned. Using the 0 as False in the next two lines can also show this.
Ultimately, I'm generally happier using Boolean values in boolean statements. Depending on non-booleans being associated with boolean values always makes me uneasy. Also, if you thibk of constructing a boolean staement with boolean values, this idea of returning the value that determines the value of the entire statement makes more sense (to me, anyway)
Post a Comment for "Python Logical Operators"