Десятичный преобразователь в двоичный в python только с использованием простых функций

Теоретически этот код должен уметь преобразовывать десятичные числа в двоичные, но продолжает возвращать ошибку трассировки.

decimal = int(input("Enter number: "))

string1 = ""

while decimal>0:
    bit = decimal%2
    quoteint = decimal/2
    str1.append(bit)# append the bit to the left of any previous bits
    number = quoteint
print (str1)

or

decimal = int(input("Enter number: "))

string1 = ""

while decimal>0:
    bit = decimal%2
    quoteint = decimal/2
    str1 = str1 + bit # append the bit to the left of any previous bits
    number = quoteint
print (str1)

Может ли кто-нибудь объяснить, почему это не работает, и если есть возможность это исправить? Я могу ошибаться в этом, так как я исхожу из этого: http://chortle.ccsu.edu/assemblytutorial/zAppendixH/appH_4.html

Идея состоит в том, чтобы создать конвертер десятичной системы в двоичную, используя только простые функции в Python.

Спасибо.


person Community    schedule 28.04.2016    source источник
comment
Я думаю, что str1 = str1 + bit должно быть string1 = string1 + bit (очевидно, корректируя первый пример соответствующим образом. Так как str1 выглядит так, как будто он будет нулевым.   -  person Michael Albers    schedule 28.04.2016
comment
Когда decimal когда-либо будет равно 0?   -  person Ignacio Vazquez-Abrams    schedule 28.04.2016


Ответы (1)


Это может помочь. Я создал функцию под названием divi, которая возвращает остаток от деления числа на 2.

def divi(y):
"""This function returns the remainder of a number when divided by 2 """
mod=y%2
return mod

Затем я использовал это, чтобы создать список остатков. Это делается повторным делением по модулю num//2 до тех пор, пока num не достигнет 1.

num=int(input("enter a decimal number "))
b=num    # Assigning the value of num to a variable b for 
later reference
lst=[]   # Defining a list
while(num>=1):
lst.append(divi(num)) #making a list having all the 
remainders when num is divided by 2 until num approaches 1
num=num//2

Затем я перевернул список, чтобы получить двоичное число.

v=list(reversed(lst))      #reversing the list above to get 
the binary form
str1=''.join(str(e) for e in v)  # converting the list to a 
string and then joining them together
print("The binary form of {} is {} ".format(b,str1))
person KUNAL DUTTA    schedule 17.11.2018