Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Function 为什么不是';我的回执不起作用吗?_Function_Python 3.x_Binary_Converter - Fatal编程技术网

Function 为什么不是';我的回执不起作用吗?

Function 为什么不是';我的回执不起作用吗?,function,python-3.x,binary,converter,Function,Python 3.x,Binary,Converter,我有一个将十进制值转换为二进制的函数。我知道我的逻辑是正确的,因为我可以让它在函数之外工作 def decimaltobinary(value): invertedbinary = [] value = int(value) while value >= 1: value = (value / 2) invertedbinary.append(value) value = int(value) for n, i

我有一个将十进制值转换为二进制的函数。我知道我的逻辑是正确的,因为我可以让它在函数之外工作

def decimaltobinary(value):
    invertedbinary = []
    value = int(value)
    while value >= 1:
        value = (value / 2)
        invertedbinary.append(value)
        value = int(value)
    for n, i in enumerate(invertedbinary):
        if (round(i) == i):
            invertedbinary[n] = 0
        else:
            invertedbinary[n] = 1
    invertedbinary.reverse()
    value = ''.join(str(e) for e in invertedbinary)
    return value

decimaltobinary(firstvalue)
print (firstvalue)
decimaltobinary(secondvalue)
print (secondvalue)

比如说
firstvalue=5
secondvalue=10
。每次执行函数时返回的值应分别为
101
1010
。但是,我打印的值是5和10的起始值。为什么会发生这种情况?

代码按预期工作,但您没有指定
返回值
ed:

>>> firstvalue = decimaltobinary(5)
>>> firstvalue
'101'
请注意,有更简单的方法来实现您的目标:

>>> str(bin(5))[2:]
'101'
 >>> "{0:b}".format(10)
'1010'

非常感谢你的帮助,非常感谢。我知道二进制转换有一种更简单的方法,但是我想使用这种方法来帮助确保我理解转换的算法。