NewtoJava
NewtoJava

Reputation: 49

Python recursion confusion

def recursion(x):
    answer = 0
    if( x > 10 ):
        answer +=1
        return recursion( x - 1)
    return answer
recursion(15)

I'm just playing around with python and recursive functions and made this, but strangely having errors.

Why is this printing 0 instead of my expected answer of:

5

Upvotes: 0

Views: 152

Answers (6)

melalonso
melalonso

Reputation: 228

What is happening is that every time you call recursively the function the value of answer is set to 0. You can change it to:

answer = 0

def recursion(x):
    global answer
    if( x > 10 ):
        answer += 1
        return recursion( x - 1)
    return answer

recursion(15)

And a better implementation would be:

def recursion(x):
    if( x > 10 ):
        return 1 + recursion(x - 1)
    return 0

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 114088

you need to add the recursive call to your answer, not return it

def recursion(x):
    answer = 0
    if( x > 10 ):
        answer = answer + 1 + recursion( x - 1)
    return answer

sometimes it is helpful to step through your code ... debuggers do this excellently, however you can also use pythontutor.com to visualize execution.

this will visually show you what happened with your old code and why it was broken

Upvotes: 3

Santos
Santos

Reputation: 194

The variable answer allways return 0.

A better solution would:

def recursion(x, answer):
    if( x > 10 ):
        answer +=1
        return recursion( x - 1, answer)
    return answer
recursion(15, 0)

Upvotes: 0

Ruru Qian
Ruru Qian

Reputation: 1

Cuz your answer is a local variable,every time you call the function,there is a "new answer para",just like that:

recursion(15):answer=0 answer+=1

recursion(14):answer=0 answer+=1

...

recursion(10):answer=0 jump if then return the answer to recursion(11), then to recursion(12)...... the right way for your program should be:

answer = 0
def recursion(x):
    global answer
    if( x > 10 ):
        answer +=1
        return recursion( x - 1)
    return answer

Upvotes: 0

KIDJourney
KIDJourney

Reputation: 1230

Because the answer you define is in local scope .

It means the answer in this function call is not the same as in last call .

Your code should be

def recursion(x , answer):
    if( x > 10 ):
        answer +=1
        return recursion( x - 1 , answer)
    return answer
print(recursion(15 , 0))

Upvotes: 1

l'L'l
l'L'l

Reputation: 47282

You need to make answer a global variable:

answer = 0

def recursion(x):
    global answer
    ...

Upvotes: 1

Related Questions