Home > other >  Using a loop to convert decimal to binary
Using a loop to convert decimal to binary

Time:10-25

I want to write a program that coverts 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 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)

CodePudding user response:

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

CodePudding user response:

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
  • Related