0

I'm trying to check if integer number is palindrome but my code always returns false.

def checkPalindrome(num):
    rev = 0
    while num != 0:
        d = num % 10
        rev = (rev * 10) + d
        num = num // 10
    print(rev)
    if num==rev:
        return True
    else:
        return False

print(checkPalindrome(1)) 
Jeff Zeitlin
  • 9,773
  • 2
  • 21
  • 33
  • Does this answer your question? [How to check for palindrome using Python logic](https://stackoverflow.com/questions/17331290/how-to-check-for-palindrome-using-python-logic) – Alexei Levenkov Oct 18 '22 at 17:46
  • You may want to add `print(num)` next to `print(rev)`... Otherwise just copy-paste existing solutions for the same problem. – Alexei Levenkov Oct 18 '22 at 17:52
  • 1
    Note that normally you should not tag question with two languages - the code shown in the post does not look like BASIC - are you looking to translate the code to BASIC? Also make sure to clarify why this is Python 3 specific - usually questions should be tagged with just "python" unless there is significant difference between versions and the question is specifically about 3.x versions. – Alexei Levenkov Oct 18 '22 at 17:54

1 Answers1

0

The code which you wrote

def checkPalindrome(num):
    rev = 0
    while num != 0:
    d = num % 10
    rev = (rev * 10) + d
    num = num // 10
    print(rev)
    if num==rev:
        return True
    else:
        return False

In this line num = num // 10 num is replaced by num/10 and in next if condition you are checking num==rev which is always false. So how many times you give a value it always gives you false.

So if you store num in a temporary variable i.e, tempVariable=num so that you when you reverse the num you can check the original value with tempVariable and then do num = num // 10 and in next if condition you can check tempVariable==rev which will give you correct result.

Following code will give you correct result for numbers

def checkPalindrome(num):
    tempVariable = num
    rev = 0
    while num != 0:
        d = num % 10
        rev = (rev * 10) + d
        num = num // 10
    if tempVariable == rev:
        return True
    else:
        return False

num = int(input())
isPalindrome = checkPalindrome(num)
if (isPalindrome):
    print('true')
else:
    print('false')