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'
None
答案 0 :(得分: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
递归调用就像任何其他函数调用一样,如果你不对返回值做任何事情,它就会被丢弃。递归调用不会将其结果神奇地传递给最外层的调用。
答案 1 :(得分:2)
你忘了返回递归的结果。
return counter(a,count)