How is boolean "And" different from '&' ? (In Python) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How is boolean "And" different from '&' ? (In Python)

6th Jun 2018, 9:39 AM
Sandeep Singh
Sandeep Singh - avatar
8 Answers
+ 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!
6th Jun 2018, 1:47 PM
Brian
Brian - avatar
+ 1
That is just different syntax for different languages. What languages were you referring to?
6th Jun 2018, 9:41 AM
Fabio Rocha
Fabio Rocha - avatar
6th Jun 2018, 9:43 AM
Sandeep Singh
Sandeep Singh - avatar
0
and is boolean and & is bitwise but bitwise can give different behavior than and if used on truthy or falsy values
6th Jun 2018, 12:39 PM
Max
Max - avatar
0
Brian Max can you please use '&' in a program to contrast it's operation in a program
9th Jun 2018, 4:00 PM
Sandeep Singh
Sandeep Singh - avatar
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
11th Jun 2018, 2:02 AM
Brian
Brian - avatar
0
Brian thanks alot
11th Jun 2018, 3:03 PM
Sandeep Singh
Sandeep Singh - avatar
0
Sandeep Singh You are welcome.
11th Jun 2018, 3:16 PM
Brian
Brian - avatar