2015-04-26 178 views
0
def counter(number,count): 
    if (number!=1 and number%2==0): 
     a=number/2 
     count=count+1 
     counter(a,count) 
    elif (number!=1 and number%2!=0): 
     a=3*(number)+1 
     count=count+1 
     counter(a,count)   
    else: 
     print count 
     return count 

z=counter(13,0) 
print z 

count評估爲9並且它會打印它,但不會返回它嗎?打印'z'時說NonePython函數返回null

回答

3

你忽略了遞歸調用;添加return語句,你在counter本身撥打counter()

def counter(number,count): 
    if (number!=1 and number%2==0): 
     a=number/2 
     count=count+1 
     return counter(a,count) 
    elif (number!=1 and number%2!=0): 
     a=3*(number)+1 
     count=count+1 
     return counter(a,count)   
    else: 
     print count 
     return count 

遞歸調用就像任何其他函數調用,如果你不這樣做有它只是丟棄的返回值什麼。遞歸調用不會將其結果神奇地傳遞給最外層的調用。

2

你忘了返回遞歸的結果。

return counter(a,count)   
+0

非常感謝你們!看起來很傻 – user1468460