【问题标题】:Why isn't my return statement working?为什么我的退货声明不起作用?
【发布时间】:2017-04-06 08:04:11
【问题描述】:

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

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 = 5secondvalue = 10。每次执行函数时返回的值应分别为1011010。但是,我打印的值是 5 和 10 的起始值。为什么会这样?

【问题讨论】:

    标签: function python-3.x binary converter


    【解决方案1】:

    代码按预期工作,但您没有分配 returned 值:

    >>> firstvalue = decimaltobinary(5)
    >>> firstvalue
    '101'
    

    请注意,有更简单的方法可以实现您的目标:

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

    【讨论】:

    • 非常感谢您的帮助,非常感谢。我知道二进制转换有一种更简单的方法,但是我想使用这种方法来帮助确保我理解转换的算法。
    猜你喜欢
    • 2015-09-30
    • 1970-01-01
    • 2014-08-21
    • 2013-07-13
    • 2015-04-28
    • 2016-12-26
    • 1970-01-01
    • 2013-08-10
    • 2020-06-15
    相关资源
    最近更新 更多