2015-12-02 40 views
0

使用重复的部门如何十进制转换为二进制通过使用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 

谢谢

+0

您是否收到任何错误? – hdost

+0

正确的pep8格式 –

回答

0

制作一个“破发”,没有任何条件,使循环没用,所以代码只执行一次,不管是什么。

-

如果您不需要保留原来的号码,你可以改变“数量”,当您去。

如果您确实需要保留原来的号码,你可以像“时代”不同的变量。

你似乎这两种情况混合在一起。

-

如果你想打印的所有步骤,打印将在循环内部,它打印多次。

如果你只想打印最终结果,则刊出外循环。

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 

赋值运算符右侧=首先evaulated。

的=右侧是

str(remainder) + result 

,正如我们去了上述具有值:

"0" + "11010" 

这是字符串连接。它只是把一个字符串放在另一个字符串的末尾。结果是:

"0  11010" 

"011010" 

这是在赋值语句右侧评估的值。

result = "011010" 

现在这就是结果的值。

+0

谢谢你哟,还有一个问题...我需要知道...什么是“str(余数)+结果”呢?特别是余下的“str”函数,它做什么......这使得这段代码有效。预先感谢 – hameed

+0

你能解释一下吗...“str(余数)+结果”是什么?特别是“str”函数之前的其余部分..呢? @beauxq – hameed

+0

@hameed添加到答案 – beauxq