Search code examples
pythonpalindrome

Why am I seeing error when the number is 001? Please look at the code below to find the maximum palindrome sum from a given number


With number = 001, the error is 'invalid token'.. Please explain why and why 1 and 001 is not treated the same way by the compiler?

number = 001

def palindrome(number):
    print ("The number is: ",number)
    str1 = str(number)
    strrev = str1[::-1]

    if (str1 == strrev):
        return True
    else:

        a = int(str1)
        b = int(strrev)
        c = a+b
        print ("Sum with reverse: ",c)
        print ("    ")

        return (palindrome(c))

n = palindrome(number)

print ("Palindrome: ",n)

Solution

  • 001 is an integer it will work as 1, instead of 001. If you need 001 use it as string not an integer. As 001 is invalid integer, but when it comes to string variable it works fine.

    Use :

    stringNumber = '001'