Three Reliable Ways to Detect Palindromes in Python
This article tackles a basic Python problem—determining whether a positive integer is a palindrome—by analyzing the original flawed code and presenting three complete solutions: a for‑else approach, an all()‑based method, and a slice‑reversal technique, while also clarifying how the for‑else statement operates.
In a Python discussion group a user asked how to correctly determine whether a positive integer is a palindrome. The original code attempted the check but placed the result output in the wrong location.
1. Original Code
x=input("请输入一个正整数:")
long=len(x)
end=str(x[long-1])
end=int(end)
x=int(x)
if x<0 or end ==0:
print("不是回文数")
else:
x=str(x)
for i in range(len(x)):
if x[i]==x[long-i-1]:
continue
else:
print("不是回文数")
break
print("是回文数")2. Solution 1 – Using for‑else
Placing the success message inside the else clause of the for loop ensures it runs only when the loop completes without breaking.
x=input("请输入一个正整数:")
long=len(x)
end=str(x[long-1])
end=int(end)
x=int(x)
if x<0 or end ==0:
print("不是回文数")
else:
x=str(x)
for i in range(len(x)):
if x[i]==x[long-i-1]:
continue
else:
print("不是回文数")
break
else:
print("是回文数")3. Solution 2 – Using all()
d = ['12321', '123', '1221', '1212']
for s in d:
l = len(s)
if all(s[i] == s[l-i-1] for i in range(l)):
print(f'{s}是回文数')
else:
print(f'{s}不是回文数')4. Solution 3 – Using Slice Reversal
d = ['12321', '123', '1221', '1212']
for s in d:
if s == s[::-1]:
print(f'{s}是回文数')
else:
print(f'{s}不是回文数')5. Why for‑else Works
The else block attached to a for loop executes only when the loop finishes normally, i.e., without encountering a break. This makes it ideal for signalling that all characters matched and the number is a palindrome.
Conclusion
The three approaches above reliably solve the palindrome‑checking problem, each illustrating a different Python technique—loop control with for‑else, collective condition checking with all(), and concise slicing.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
