Python Program to Check a Palindrome Number
Beginner Numbers
Checks whether a number reads the same backwards as forwards by reversing its digits and comparing.
A palindrome reads the same backwards as forwards. 12321 is a palindrome number, and so is every one-digit
number; 12345 isn't, as backwards it's 54321. The program reverses the number's digits with % 10 and // 10, then
compares the result with the number it started with.
Program
def is_palindrome(number):
"""True if number reads the same backwards as forwards."""
remaining = number
reversed_number = 0
while remaining > 0:
digit = remaining % 10
reversed_number = reversed_number * 10 + digit
remaining //= 10
return reversed_number == number
print("12321:", is_palindrome(12321))
print("12345:", is_palindrome(12345))
Open in the editor Download palindrome_number.py
Output
12321: True
12345: False
How it works
Step through the program line by line: each step below shows up as its line runs.
-
remainingis a copy of the number for the loop to take apart, sonumberkeeps its value for the comparison at the end. -
reversed_numberstarts at 0 and is built up one digit at a time. - The loop runs while
remaininghas digits left. -
remaining % 10is its last digit. Multiplyingreversed_numberby 10 makes room at its end, and the digit goes there. -
//= 10removes that digit, so the next round takes the one before it. - The number is a palindrome when its reverse is the same number.
==givesTrueorFalse, which the function returns. - The program checks 12321, which is a palindrome, and 12345, which reverses to 54321.
For 12321, reversed_number grows to 1, 12, 123, 1232 and 12321, which equals the number.
Other ways to write it
With str() and slicing
As text, the check is one comparison: text[::-1] is the text reversed (strings). This version
works for words too.
def is_palindrome(number):
text = str(number)
return text == text[::-1]
print(is_palindrome(1221), is_palindrome(1231))Comparing digits from both ends
This version compares the first digit with the last, the second with the second-last, and so on, and stops at the first pair that differs. For a long number that isn't a palindrome, one comparison can be enough.
def is_palindrome(number):
digits = str(number)
left, right = 0, len(digits) - 1
while left < right:
if digits[left] != digits[right]:
return False
left += 1
right -= 1
return True
print(is_palindrome(1234321), is_palindrome(1234521))Try it yourself
- Check 7, 1221 and 120. 120 isn't a palindrome, as its reverse is 21.
- Print the palindromes from 100 to 200 with a loop: there are 10, from 101 to 191.
- Check a word such as
"level"with thestr()version, then make"Level"work too with.lower(). - Reverse and add until you reach a palindrome: 87 + 78 = 165, 165 + 561 = 726, 726 + 627 = 1353, and 1353 + 3531 = 4884.