1

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')
timgeb
79.2k20 gold badges129 silver badges150 bronze badges
asked Feb 18, 2020 at 7:05
1
  • 2
    Because 15&5 will evaluate to 5 and 5 never equals to 0. Commented Feb 18, 2020 at 7:09

4 Answers 4

4

& is bitwise AND and works like this:

15 & 5

 1111
& 0101
------
 0101 != 0
answered Feb 18, 2020 at 7:11
Sign up to request clarification or add additional context in comments.

Comments

3

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.

answered Feb 18, 2020 at 7:11

Comments

3

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.

answered Feb 18, 2020 at 7:14

Comments

1

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

answered Feb 18, 2020 at 7:25

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

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.

Ask question

Explore related questions

See similar questions with these tags.