Here this example will help us learn how to judge if a number is a palindrome in Python.
If the number n reads the same backward as forward, it is a palindrome. For example if n = 1234321, n is a palindrome, it is not if n = 1234123.
Method
- Convert the input number to a string type for easy processing.
- The element of index (i) is to be compared with the element of index (-i-1).
- Stop comparison until reaching the middle of the string.
Source Code
#!/usr/bin/python
# -*- coding: UTF-8 -*-
a = int(input("Please input a number: "))
x = str(a)
flag = True
for i in range(int(len(x)/2.0)):
if x[i] != x[-i - 1]:
flag = False
break
if flag:
print("%d is a palindrome!" % a)
else:
print("%d is not a palindrome!" % a)
Output:
Please input a number: 334543343
324543343 is not a palindrome!
Please input a number: 233454332
233454332 is a palindrome!