This question already has answers here:
Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?
(3 answers)
Closed 8 years ago.
Can someone help to explain the following:
1 and 5
5 and 1
The above gives 5 and 1 respectively. Q1: Why is the and operator not commutative?
Next:
1==True # gives True
However:
5==True
5==False
both give False. Q2: Why?
https://docs.python.org/2/library/stdtypes.html section 5.1 says "... All other values are considered True", so 5 should be True.
From the documentation:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
Note that here, if x is false means if bool(x) == False.
The answer to your first question about and is that the result of the and is the value of the first expression if it is False-like (0, False, None, etc.), otherwise it is the value of the second expression. A bunch of programming languages share this sort of construct; in some languages like Bash and Perl it's idiomatic to rely on it extensively. In Python we mostly use and for regular boolean logic and rely on it less often for short-circuiting.
As for 1==True being true but 5==True being false, well, frankly I wish 1==True also returned false but obviously it's too late to change it now. :)
In answer to your second part:
It's true that all non-zero integers are "Truthy" but this does not mean that 5 == True will return True. The == operator is comparing value and, when comparing values, 5 is not equal to True. If you compare bool(5) == True then that will return True. When you do if 5: what you actually are doing is if bool(5):.
The reason that 1 == True returns True is that in Python the boolean class is a subclass of int, with True being represented by 1 and False being represented by 0. So 1 == True returns True because they are equal.
Note that, as discussed in this question, this is NOT GUARANTEED in Python 2.x as True and False can be re-defined. In Python 3.x they are keywords which will always be equal to 1 and 0, respectively.
Related
This question already has answers here:
How do "and" and "or" act with non-boolean values?
(8 answers)
Closed 11 months ago.
Just starting out learning Python. Is the reason for not(True or False) returning False because:
"True or False" is not a Falsy. Hence, not Falsy = Truthy. Therefore, not(Truthy) = False; or
For example, "bag" > "apple" will return True because Python takes the first string to compare, which is "b" and "a" and b is greater than a; therefore, True is returned. Applying the same logic, Python will only take the first statement in (True or False), which would be True and hence, not(True) = False; or
It has something to do with the order of precedence for "not" and "or" operators, which I don't quite grasp and would really appreciate any explanations.
Thank you!
This is the truth table of (a or b) & not (a or b)
As you can see in the 3rd line (on the right) if you take a = True, b = False then the result will be False
Evaluating the expression in order:
(True or False) = True Due boolean algebra
not (True or False) = not (True) = False As you are negating True so is False
Python interprets True and False as booleans, and in the context of booleans "not", "or", "and" will behave exactly as boolean operators, even if they support other type operands.
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
Why does the following evaluates to False in Python?
6==(5 or 6)
False
'b'==('a' or 'b')
False
The first expression evaluates (5 or 6) first, which evaluates to 5 because 5 is truthy. 5 is NOT equal to 6 so it returns False.
The second expression evaluates ('a' or 'b') first, which evaluates to 'a' for the same reason as above. 'a' is NOT equal to 'b' so it returns False.
A good example to explain this would be to try to put a falsey value as the first part of the or expression like 6 == ([ ] or 6) or 6 == (None or 6). Both of these will return true because the or statement will evaluate to the truthy value (in each case it is 6).
There are a couple of ways to create the statement I think you want. The first would be to use in like 6 in (6,5). The second way would be to expand your boolean expression to read like this (6 == 5) or (6 == 6). Both of these will return True.
The condition within parentheses is evaluated first. So
6==(5 or 6)
evaluates to
6==(5) # since 5 != 0 (True), the second operand is not evaluated
which is False. Same goes for the second one. ('a' != None)
Try:
>>>6 == (6 or 5)
True
What's going on? Try:
>>5 or 6
5
I'm not totally sure why "5 or 6" evaluates to 5, but I would just try writing that expression differently.
But there is a caveat:
>> 5 == (0 or 5)
True
Because 0 is not truth-worthy, hence the bracket result in 5.
This question already has answers here:
and / or operators return value [duplicate]
(4 answers)
What does "variable or 0" mean in python?
(4 answers)
Closed 7 years ago.
In Python, if I write
z = 1 and 2
print z
Then it yields "2".
But if I write
z = 0 and 2
print z
Now, it yields "0".
It may not be much important in real life problem, but I'm trying to understand the logic here.
0, [], "" are all false-ish (they are treated as False in a python condition). and returns the first false-ish value or the last one. This is called short-circuit evaluation. That's why in one case it returns 2 (the last) and in the other it returns 0 (the false-ish).
In fact if you think about the logic operation, you can short-circuit this behaviour:
x and y (with x false-ish) -> x
x and y (with x true-ish) -> y
When plugged into a condition it will evaluate as:
In the first case it evaluates the boolean result of x which is False. This is the correct result for the and operation, since False and y = False for any y.
In the second case it evaluates the boolean value of y. Since x is True, the result of and should be False when y is False and True when y is True (it reflects the value of y).
c = a and b
is the same as
if a:
c=b
else:
c=a
I think more interesting is or:
c = a or b
is the same as
if a:
c=a
else:
c=b
Note also that if a: is a short way of if bool(a):. bool returns False for this objects/values:
None, 0, False, "", [], tuple(), dict(), set()
As you can see, they are all somehow empty...
The and operator in python short circuits. That is: it only evaluates enough operands (from left to right) as are necessary to determine whether the outcome is True or False. The result of and is False so in the second case, where 0 evaluates to False, and returns 0, but as 1 is True, the second operand must also be evaluated and returned.
0 is treated as False and anything above zero is treated as True so z = 1 and 2 sets z equal to 2 and z = 0 and 2 is 0 because it evaluates to False.
consider this code:
>>> 0 and True
0
>>> 0 and False
0
Why do I get 0 when I run the above commands in Python?
When the first condition of an and evaluates to False (which 0 does in Python), the second argument is not evaluated at all, because the and will never become true. This is called short-circuiting. In that case, the result of the expression is the first operand, in your case 0.
Because 0 is a false value (all numeric 0 values are, as well as empty containers, and None and False).
The and operator short-curcuits; if the left-hand expression evaluates to a false value, it is returned, otherwise the right-hand expression outcome is returned.
The or operator does the same, but for a true left-hand value; 1 or False returns 1.
From the Boolean operations documentation:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
You can make handy use of this:
foo = None
if something_or_other:
foo = lambda arg: arg * 3
outcome = foo and foo('bar')
outcome = foo or expensive_call()
where foo is only called if it is actually defined and not still None; the expensive_call() is only invoked if foo is not yet bound to a true value.
You are ANDing with zero. You should get zero always.
this is because, logical operators are evaluated from left to right. So, for or if True find rest of the expression not evaluated:
>>> True or "one"
True
>>> False or "one"
'one'
Similarly for and, if False found rest of the expression ignored:
>>> True and "one"
'one'
>>> False and "one"
False
In compiler design, this concept is called short-circuiting and this is same design for most of compilers.
most of programming languages have this feature, it's fast branch detection, in your case and if first condition is false, evaluation is fail and second (other) condition never check
in other case or if first condition return true second (other) condition never check and result will be true
it's really cool feature look this sample for example:
if( list != null and !list.isEmpty() ) {
// do stuff
}
if this feature does not exists this if statement cause exception, but now !list.isEmpty() will never runs when list is null
My first question is what is the more abstract question for the question: 'what is the operation that returns 6 for the expression (2 and 2*3)? Please feel free to retitle my question appropriately.
My second question is what is it that is going on in python that returns 6 for (2 and 2*3). There seems something elegant going on here, and I'd like to read up on this operation.
From the Python language reference:
Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument.
As such, 2 and 2*3 means it first evaluates bool(2), which evaluates to True, and then it evaluates bool(2*3) which evaluates to True. Therefore it'll return the last evaluated argument, which is 2*3 (6).
According to the python docs
x and y : if x is false, then x, else y
First you have to read this and then you have to read this. :)
After that you will know that and is a boolean operator, that tries to convert it's first operand to boolean. So if you read the first thing you will see that 2 is converted to True.
The third thing you need to know is that the and operand will return it's first argument if it is converted to False and it's second argument if it evaluates to True.
So basically
z = x and y
Can be translated to:
if x:
z = y
else:
z = x
And now you understand everything. :)
2 is evaluated to True and then and operator returns the value of it's second argument which is 6.
Applying lazy evaluation, python return for a and b a if a evaluates to False and b if a evaluates to True.
Hence 2 evaluates to True, 2 and 2*3 return 2*3 which equals 6.
Basically it's same as 2 and 6.
How it works? and returns first element if it's considered False (False, 0, [] ...) and return second otherwise
This is to do with how Python evaluates the expression x and y. It returns y if x is True, and x if x if False.
So, in case of 2 and 2 * 3, since 2 is evaluated to True, it would return the value 2 * 3, which is 6.
In case of and operation between multiple operands, it returns the 1st non-True value, and if all the values are True, it returns the last value.
Similarly, for or operator, the expression say, A or B or C, returns the 1st True value. And if all the values are False, it returns the last value.