How do and
/or
operators work between numbers (or even strings)?
5 and 7 # this returns 7
7 and 5 # this returns 5
21 and 4 # this returns 4
4 and 21 # this returns 21
How does the and
operator work in such cases?
How do and
/or
operators work between numbers (or even strings)?
5 and 7 # this returns 7
7 and 5 # this returns 5
21 and 4 # this returns 4
4 and 21 # this returns 21
How does the and
operator work in such cases?
AND/OR :
5 and 7 #7
It check 5 first and found it is 'True' so it check for second also and return last one.
0 and 5 # 0
it check for first and found is zero so whatever will be next value it is always zero so it return 0
2 or 3 and 4 #2
first value is 2 ('True') and found OR So value is always true so return 2
(2 or 3) and 4 #4
now return 4.
It returns the last value which is True
(if there is any True value).
For an and
python needs to check every value, so if they are all true then it returns the last one, if one of them is False, then it returns that value. If all of them are False it returns the first one because Python doesn't need to check the second one as well.
For an or
python checks first the first one until he gets True sometime, so if the first value is True it returns this value, if the first one is False but the second one is True, it returns the second one. If they are all False it returns the last one.
The values which are equivalent to False: "",0,False,0j, 0.0, [], {}, set()
.
When and
is used with integers, it will give you the last value if all value are non-zero, or zero if there's at least one.
1 and 2 and 3 #3
1 and 0 and 3 #0
Let's disassemble!
>>> import dis
>>> def check_and(a, b):
... return a and b
...
>>> dis.dis(check_and)
2 0 LOAD_FAST 0 (a)
3 JUMP_IF_FALSE_OR_POP 9
6 LOAD_FAST 1 (b)
>> 9 RETURN_VALUE
Now it's pretty straightforward.
1. Load a to stack (It becomes TOS
- Top of stack value.
2. JUMP_IF_FALSE_OR_POP tries to evaluate boolean value of TOS (Top Of Stack). If it's true, remove this value from stack, if it's not, set bytecode counter (in our case it would junmp to line 9.
3. Push b to stack.
4. Return.
I can't really tell why the evaluation order is different in the other case but as you can see the second evaluated value will be returned if first one is True
.
Same happens to or
and other operators. try to disassemble them yourself.
This comes handy if you want to make a quick check. Instead of writing:
def check(value)
if value:
return value
else:
return "No value"
You can write:
def check(value):
return value or "No value"