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'

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.

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)        

Comments

Your Answer

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.