0

Can someone explain me the difference between these two codes?

def pal(s):
    if s == "":
        return True
    if s[0] != s[-1]:
        return False
    return pal(s[1:-1])

a = "anna"

print(pal(a))

and

def pal(s):
    if s == "":
        return True
    if s[0] != s[-1]:
        return False
    pal(s[1:-1])

a = "anna"

print(pal(a))

Why the firts one return the right value, that is True, and the second return me None?

  • If you have more than 1 iteration, you have a recursive process. In the 2nd code, you just ask to compute the same function , but you don't ask for a return in the end. The thing returned will be the thing inside your "return" block of the 1st iteration, so if you don't call `return` before the `pal(s[1:-1])` the function will just compute the thing but not return anything – Adept Sep 23 '20 at 14:29
  • Ok but when I arrive at the last iteration(recursion) with the empty string, shouldn't it returns "True"? –  Sep 23 '20 at 14:51
  • It changes the code in **the same way** that it would change the code if you did **the same thing** with **any other** function call. Returning the value vs. just getting that value and ignoring it. – Karl Knechtel Aug 13 '22 at 00:43

1 Answers1

1

The first one is returning the value of recursive solution with the line:

return pal(s[1:-1])

Whereas the second one is just returning a void/None, and not the solution of recursive method.

Hashir Baig
  • 2,162
  • 15
  • 23