Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
Can someone tell me why I'm getting 4 as the outcome? Should 3 be printing instead because the code is satisfied in the If section.
a = 15 if a&5 == 0: print('3') elif a% 5 == 0: print('4') else: print('5')
15&5
5
0
& is bitwise AND and works like this:
15 & 5
1111 & 0101 ------ 0101 != 0
Add a comment
You are comparing the bits of 15 with the bits of 5, resulting in the ones they have in common.
1111 & 101 => 101
so the result is 5, not 0.
The "&" operator is a Bitwise AND so in your code it is like:
1111 & 0101 = 0101
That means
15 and 5 = 5
So the first condition can not be true and you'll get 4 in output because the reminder of 15/5 is 0.
4
15/5
If you want to check LSB then you should do "and" with 1 and check the result if it's 1 then LSB is 0 else LSB is 1
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.
15&5will evaluate to5and5never equals to0.