nutella1555
nutella1555

Reputation: 39

How to use loops to convert a decimal to binary?

I want to write a program that converts the decimal numbers 0 to 9 into binary. I can code how to convert a decimal number to binary using repetitive division. However, I am having trouble with creating a loop that will print out the decimal numbers 0 to 9 in their binary format.

Here is my code

number = 0

remainder = 0
x = ""
while number (0,9):
    remainder = (number%2)
    x = str(remainder) + x
    number = number//2
   
    (x[::-1])
    print(number, "is the binary of",x)

Upvotes: 0

Views: 2968

Answers (2)

mozway
mozway

Reputation: 261964

Here is a fix of your code:

number = 123
remainder = 0
x = ""
n = number # don't work on the original number
           # you need it for the final print
while n > 0:  # wrong syntax for the condition
    remainder = (n%2)
    x = str(remainder) + x
    n = n//2
    #(x[::-1])  # this is useless
print(x, "is the binary of", number) # wrong order to print

NB. You should also take advantage of divmod, instead of the two separate % and // operations

Upvotes: 1

Red
Red

Reputation: 27577

Here is what you can do:

number = 5
n = number
x = ""
while n:
    x = str(n % 2) + x
    n //= 2
    
print("Decimal:", number)
print("Binary:", x)

Output:

Decimal: 5
Binary: 101

Upvotes: 0

Related Questions