PythonMastery

Palindrome number program in Python

Check whether a number reads the same forwards and backwards, like 12321, with string slicing and with a digit-by-digit loop.

A palindrome number reads the same from left to right and from right to left. 121, 4554 and 7 are palindromes. 123 is not.

The program

python
n = int(input("Enter a number: "))

text = str(n)
if text == text[::-1]:
    print(f"{n} is a palindrome")
else:
    print(f"{n} is not a palindrome")

Typed in this example: 12321. Press Run to type your own.

output
Enter a number: 12321
12321 is a palindrome

How it works

Another way: without strings

This version reverses the digits with arithmetic, as on the reverse a number page, and compares the result with the original:

python
def is_palindrome(n):
    if n < 0:
        return False
    original = n
    reversed_number = 0
    while n > 0:
        reversed_number = reversed_number * 10 + n % 10
        n //= 10
    return reversed_number == original


for n in [121, 4554, 123, 7, 10, -121]:
    print(n, is_palindrome(n))
output
121 True
4554 True
123 False
7 True
10 False
-121 False

Related programs: Palindrome string.

Learn the idea: Working with Strings, Control Flow: Conditionals