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 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
asked Apr 26, 2015 at 16:50

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

You forgot to return the result of recursion.

return counter(a,count) 
answered Apr 26, 2015 at 16:53

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.