为什么我的 return 语句不起作用?
Why isn't my return statement working?
我有一个将十进制值转换为二进制值的函数。我知道我的逻辑是正确的,因为我可以让它在函数之外工作。
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 的起始值。为什么会这样?
代码按预期工作,但您没有分配 return
ed 值:
>>> firstvalue = decimaltobinary(5)
>>> firstvalue
'101'
请注意,有更简单的方法可以实现您的目标:
>>> str(bin(5))[2:]
'101'
>>> "{0:b}".format(10)
'1010'
我有一个将十进制值转换为二进制值的函数。我知道我的逻辑是正确的,因为我可以让它在函数之外工作。
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 的起始值。为什么会这样?
代码按预期工作,但您没有分配 return
ed 值:
>>> firstvalue = decimaltobinary(5)
>>> firstvalue
'101'
请注意,有更简单的方法可以实现您的目标:
>>> str(bin(5))[2:]
'101'
>>> "{0:b}".format(10)
'1010'