Fishhy
Fishhy

Reputation: 35

Outputs Wrong Number Decimal to Binary?

I have tried to follow an exercise from a book however my output prints a long number which includes numbers 1-10 I know there is something wrong with my code as binary is represented with 0s and 1s. Is the Below is my code:

num = int(input("enter a number"))
def bin(num):
    conversion = num
    string_y =  ""
    while conversion > 0:
        string_y = str(conversion // 2) + string_y
        conversion = conversion // 2
    return string_y

print(bin(num))

Upvotes: 0

Views: 31

Answers (1)

MahdeTo
MahdeTo

Reputation: 11184

str(conversion // 2)

Should be

str(conversion % 2)

Upvotes: 1

Related Questions