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]
Sikkim CbseNCERTSubjective· 3mImportance★★★★★est
95% · 37/39 Questions
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 start | n % 10 | rev = rev*10 + digit | n // 10 |
|---|---|---|---|
| 12321 | 1 | 1 | 1232 |
| 1232 | 2 | 12 | 123 |
| 123 | 3 | 123 | 12 |
| 12 | 2 | 1232 | 1 |
| 1 | 1 | 12321 | 0 → 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.