Skip to content
Programming Exercises · Q8

Q.Write a function that checks whether an input number is a palindrome or not.
[Note: A number or a string is called palindrome if it appears same when written in reverse order also. For example, 12321 is a palindrome while 123421 is not a palindrome]

West Bengal WbchseTextbookSubjective· 3mImportance★★★★★est
95% · 37/39 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

A number is a palindrome if it equals its own reverse — build the reverse digit by digit with rev = rev * 10 + n % 10, then compare.

The idea. "Reads the same backwards" means: reverse the digits and compare with the original. The reverse can be built with the same digit toolkit as a digit-sum: n % 10 peels the last digit, n // 10 discards it, and rev = rev * 10 + digit appends each peeled digit to the growing reverse (shifting rev left one place each time). Wrapping the test in a function returning True/False makes it reusable, as the question asks.

Program

def is_palindrome(num):
    # returns True if num reads the same in reverse
    n = num
    rev = 0
    while n > 0:
        rev = rev * 10 + n % 10
        n = n // 10
    return rev == num

num = int(input("Enter a number: "))
if is_palindrome(num):
    print(num, "is a palindrome")
else:
    print(num, "is not a palindrome")

Sample runs

Enter a number: 12321
12321 is a palindrome
Enter a number: 123421
123421 is not a palindrome

Trace for 12321

n at startn % 10rev = rev*10 + digitn // 10
12321111232
1232212123
123312312
12212321
11123210 → loop ends

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.