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
str(n)turns the number into a string, such as"12321".text[::-1]is the same string reversed. If the string and its reverse are equal, the number is a palindrome.- Negative numbers are never palindromes with this rule:
"-121"reversed is"121-". This is the usual convention.
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
- The loop changes
n, so the function saves the starting value inoriginalfirst. - 10 is a good test case: reversed, it becomes 1 (the zero is lost), and 1 is not equal to 10, so the answer is correctly
False.
Related programs: Palindrome string.