ps: This question was just marked as duplicate and there was already an answer. The thing is, this question is not the same as the other one. In this problem, I already know where my code was wrong. Im asking WHY it was wrong.
This is a problem on udacity that I was asked to solve:
Define a procedure is_palindrome, that takes as input a string, and returns a Boolean indicating if the input string is a palindrome.
Hint:
Base Case:
''
=>True
Recursive Case: if first and last characters don't match =>
False
If they do match, is the middle a palindrome?
def is_palindrome(s):
if s=='':
return True
else:
if s[0]!=s[-1]:
return False
else:
s=s[1:-1]
is_palindrome(s)
And the 3 input cases to try:
print is_palindrome('')
#>>> True
print is_palindrome('abab')
#>>> False
print is_palindrome('abba')
#>>> True
If I leave my code like that, it will return None for case 'abba'. It can be fixed by changing the last line of the function into
return is_palindrome(s[1:-1])
May I ask why the return
matter? Even without the return, shouldn't it just run the function is_palindrome()
over again and again?