Search code examples
pythonpython-3.xpalindrome

Code output is different than expected in palindrome function


Why am I not getting the correct output?

This is my code:

def main():
    num = 111

    if (isPalindrome(num)):
        print ("Palindrome",num)
    else:
        print ("Not a palindrome", num)


def isPalindrome(num):
    temp = num
    revNum = 1

    while temp > 0:
        rightNum = temp%10
        revNum = revNum * 10 + rightNum
        temp = temp/10

    print (revNum)
    if revNum == num:
        return True
    else:
        return False

main()

Output:

inf
Not a palindrome 111

It should return true and print Palindrome. I'm not understanding why am I not getting the output.


Solution

  • Init
        revNum = 0
    

    & use Floor division (//), normal division always results float

    temp = temp//10
    

    refer: https://www.programiz.com/python-programming/operators

    Try to debug with print statements for troubleshooting.