Python 3.x 如何在python中使用重复除法将十进制转换为二进制

Python 3.x 如何在python中使用重复除法将十进制转换为二进制,python-3.x,decimal,Python 3.x,Decimal,如何在python中使用重复除法将十进制转换为二进制 我知道我必须使用while循环,并使用模符号和其他{%}和{/}来实现这一点……但我需要一些例子来理解它是如何完成的,这样我才能完全理解。 如果我错了,请纠正我: number = int(input("Enter a numberto convert into binary: ")) result = "" while number != 0: remainder = number % 2 # gives the exact r

如何在python中使用重复除法将十进制转换为二进制

我知道我必须使用while循环,并使用模符号和其他{%}和{/}来实现这一点……但我需要一些例子来理解它是如何完成的,这样我才能完全理解。 如果我错了,请纠正我:

number = int(input("Enter a numberto convert into binary: "))

result = "" 
while number != 0:
    remainder = number % 2 # gives the exact remainder
    times = number // 2
    result = str(remainder) + result
    print("The binary representation is", result)
    break
谢谢

在没有任何条件的情况下进行“中断”,会使循环无效,因此无论发生什么情况,代码只执行一次

-

如果你不需要保留原来的号码,你可以随时更改“号码”

如果您确实需要保留原始数字,您可以创建一个不同的变量,如“times”

你似乎把这两种情况混在了一起

-

如果要打印所有步骤,打印将在循环内,因此它会打印多次

如果您只想打印最终结果,那么打印将超出循环

while number != 0:
    remainder = number % 2  # gives the exact remainder
    number = number // 2
    result = str(remainder) + result
print("The binary representation is", result)
-

连接行:

将打印放入循环中可能会帮助您了解其工作原理

我们可以举一个例子:

结果中的值可能是“11010”(一个字符串,带引号)

余数中的值可能为0(整数,无引号)

str(余数)将余数转换为字符串=“0”,而不是0

因此,当我们看到赋值语句时:

result = str(remainder) + result
首先计算赋值运算符=的右侧

=的右侧是

str(remainder) + result
正如我们上面所述,它具有以下值:

"0" + "11010"
这是字符串连接。它只是把一根绳子放在另一根绳子的末端。结果是:

"0     11010"

"011010"
这是赋值语句右侧计算的值

result = "011010"

这就是结果的价值。

您是否收到任何错误?更正pep8格式非常感谢,还有一个问题。。。我需要知道…str(余数)+结果是什么???特别是在余数之前的“str”函数,它做了什么,这使代码工作。提前谢谢你能给我解释一下吗?“str(余数)+结果”是什么意思???尤其是余数之前的“str”函数。。是吗@beauxq@hameed补充到答案中