Search code examples
python-3.xbinarymodulofloor

Why does using modulus and floor division in Python return a reversed binary number?


I'm new to programming, and I don't understand why this code returns the binary number of the input.

x = int(input())
while x > 0:
    print(x % 2, end='')
    x = x // 2

For example, when I enter 6, I expect it to return 0 (6 % 2 = 0, 0 // 2 = 0), but it returns 011.

I stated contemplating this because, in an assignment, we're supposed to use this coding to help us reverse the output (while using a string) but I don't know how to reverse it when I don't know why it works.


Solution

  • The answer of 011 is correct for your code, just trace it thru. You start with 6%2 so you get a 0. Then 6 floor 2 is 3, which is then the x for the next iteration so it becomes 3%2 which is 1 and the final iteration creates the last 1. Remember that you're not changing the value of x in the print statement, it only changes in the last line.