Mr. Kelsey
Mr. Kelsey

Reputation: 530

why can't I return my local variable from an exception in python?

During my first exploration into recursive algorithms, I ran into an oddity that I can't figure out. My function is meant to reverse a string recursively.

def revS(s, new):
    n = new
    try:
        ch = s[-1]
        n += ch
        revS(s[:-1], n)
    except IndexError:
        return n

print(revS("test", ""))

However, it just prints None. At first, I thought it might have something to do with the recursion, as if I am returning n before it has been built up. Perhaps I am. But even so, n is assigned an empty string before any recursion even begins. So at the very least, I would expect it to return an empty string rather than None Additionally, if I change my exception handling to print(n) and my call to revS("test", "") everything works as expected.

What am I missing?

Upvotes: 1

Views: 30

Answers (1)

Santiago Bruno
Santiago Bruno

Reputation: 446

It actually has to do with recursion.

Your function is only returning when there is an Exception, but in all other cases there is no return statement, so that is the same as returning None.

When you return n when there is an exception, that value goes to the calling function and so on until the first function call (your fist call to revS) and that one will return None as there is no exception.

If you change the 6th line with this it works:

revS(s[:-1], n)

to

return revS(s[:-1], n)

Upvotes: 1

Related Questions