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 is evaluated to 9 and it does print it, but won't return it? Says None when printing 'z'
Martijn Pieters
1.1m326 gold badges4.2k silver badges3.4k bronze badges
2 Answers 2
You are ignoring the recursive calls; add return statements where you call counter() in counter itself:
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
Recursive calls are just like any other function call, if you don't do anything with the return value it is just discarded. Recursive calls don't magically pass on their result to the outermost call.
answered Apr 26, 2015 at 16:52
Martijn Pieters
1.1m326 gold badges4.2k silver badges3.4k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You forgot to return the result of recursion.
return counter(a,count)
answered Apr 26, 2015 at 16:53
Ignacio Vazquez-Abrams
804k160 gold badges1.4k silver badges1.4k bronze badges
Comments
lang-py