0

I am trying to find the next pallindrome number when i an printing the num before returning it prints correctly but when i return it, it returns None

#Code starts here
def palindrome(num):
    flag=1
    copy = num
    num =num+1
    if(flag==1):
        res = [int(x) for x in str(num)]
        ser = [int(x) for x in str(num)]
        ser.reverse()
        if(res==ser):
            flag = 0
            print(num,type(num))
            return num
        else:
            palindrome(num)

a = palindrome(22)
print(a)
Shubhu
  • 23
  • 3

1 Answers1

-1

Since this is a recursive function, you need to ensure that when the recursion is finised, the values are returned and propogated up the recursion stack, which is not what is happening here.
To make sure that happens, you need ensure your recursive call palindrome(num) also returns by doing return palindrome(num), and that should fix the issue

def palindrome(num):
    flag=1
    copy = num
    num =num+1
    if(flag==1):
        res = [int(x) for x in str(num)]
        ser = [int(x) for x in str(num)]
        ser.reverse()
        if(res==ser):
            return num
        else:
            #We want to return from the recursive function as well
            return palindrome(num)

The outputs will then be

print(palindrome(46))
#55
print(palindrome(64))
#66
print(palindrome(97))
#99
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40