-1
n = int(input())
print ("conversion of {} to decimal is :".format(n) )
import math
def conv(n):
    while n!=0:
        x= n%2;
        print (int(x) , end=" ")
        n=int(n/2)
conv(n)

I want to revert print digits. in this code, I try to convert decimal to binary

petezurich
  • 9,280
  • 9
  • 43
  • 57
  • 1
    There are numerous ways to do this, the simplest of which is to just use the built-in [`bin()`](https://docs.python.org/3/library/functions.html#bin) function. You could alternatively add the bits to a list and print the whole list out at the end, or start with the high-order bits first using `n.bit_length()` to get started. Or do it recursively. – President James K. Polk Jul 10 '22 at 17:43

2 Answers2

1

the solution I found is to stock the result in a string and then read it backward with a for loop:

n = int(input())
print("conversion of {} to decimal is :".format(n))

# import math


def conv(n):
    result = ""
    while n != 0:
        result += str(n % 2)   # print (int(x) , end=" ")
        n = int(n / 2)
    for i in range(len(result) - 1, -1, -1):
        print(result[i], end = " ")

conv(n)
Cadeyrn
  • 545
  • 2
  • 12
0

If you want to convert a decimal number into binary, you should use the bin() function. The bin() function returns a string containing a binary number. So what you can do is just splice (remove) the first 2 characters from the string.

# Get the number from user
n = int(input("Enter a decimal number to convert it to binary: "))

# Converts the decimal number to binary and print it each digit with a space
binary_num = bin(n)[2:] # The [2:] removes the '0b', e.g: bin(6)[2:] returns '110'
for i in binary_num: 
    print(i, end=" ")