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')
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
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.

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.

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

Comments

Your Answer

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.