Editor

Python Program to Check a Palindrome Number

Beginner · Numbers · CBSE class 11 practical list

A palindrome number reads the same forwards and backwards, like 121, 1331 or 12321. This program reverses the digits of a number using arithmetic and compares the result with the original.

Program

palindrome_number.py
num = 12321 # or: num = int(input("Enter a number: "))
reverse = 0
temp = num # work on a copy so num stays unchanged
while temp > 0:
digit = temp % 10 # take the last digit
reverse = reverse * 10 + digit # add it to the end of reverse
temp //= 10 # drop the last digit
print("Original number:", num)
print("Reversed number:", reverse)
if num == reverse:
print(num, "is a palindrome number")
else:
print(num, "is not a palindrome number")
Output
Original number: 12321
Reversed number: 12321
12321 is a palindrome number

How it works

  1. temp % 10 takes the last digit of temp.
  2. reverse * 10 + digit shifts the reversed number one place to the left and puts that digit on the end.
  3. temp //= 10 drops the last digit, and the loop repeats until no digits are left.
  4. If the reversed number equals the original, the number is a palindrome.

Another way to write it

Using string slicing

Using string slicing
for num in [121, 12321, 123, 4554]:
text = str(num)
if text == text[::-1]:
print(num, "is a palindrome")
else:
print(num, "is not a palindrome")
Output
121 is a palindrome
12321 is a palindrome
123 is not a palindrome
4554 is a palindrome

text[::-1] gives the string backwards, so a number is a palindrome when its string equals its reverse.

Try it yourself

Change num to 12345 and check that the program says it is not a palindrome.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises