0
How is boolean "And" different from '&' ? (In Python)
8 Antworten
+ 1
Both 'And' and '&' perform the logical AND operation, but at different scales and their results are different types.
Boolean 'And' first reduces the left term to True or False. If False, the left term becomes the output result. If True, the right term becomes the result. Its output type depends upon which term becomes the result.
Bitwise '&' operates on a smaller scale and results in a numeric value. It compares each bit in corresponding positions within the left and right terms. The resulting value has each bit set to 1 only if both original terms had a 1 there. Bitwise '&' is useful for masking, which is a way to isolate specific bits. For example, you can determine whether bit 3 is set by using & to mask out all but that bit:
i = 15 // all four lower bits are 1
flag3 = i & 8 // flag3 = 8 (bit 3)
i = i & ~8 // i = 7 (clears bit 3)
In contrast, if you wrongly use Boolean 'And' for masking, (i And 8), it would only tell you whether the whole value of i is non-zero. Even if i==1, the result would be 8!
+ 1
That is just different syntax for different languages. What languages were you referring to?
0
and is boolean and & is bitwise
but bitwise can give different behavior than and if used on truthy or falsy values
0
Sandeep Singh, I edited my answer to refine and generalize how Boolean 'and' works in Python. Please read it over again.
Here is a demonstration that might be useful.
https://code.sololearn.com/cpLd2CcWLr97/?ref=app
0
Brian thanks alot
0
Sandeep Singh You are welcome.