2016-11-22 63 views
1

我有一個函數將十進制值轉換爲二進制。我知道我有正確的邏輯,因爲我可以在一個函數之外使用它。爲什麼我的return語句不工作?

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。但是,我打印的值是五個和十個的起始值。這是爲什麼發生?

回答

1

代碼按預期工作,但你沒有分配return ED值:

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

注意,有更容易的方式來實現自己的目標:

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

謝謝非常感謝你的幫助。我知道有一個更簡單的二進制轉換方法,但我想用這種方法來幫助確保我理解轉換的算法。 –

相關問題