Python Program to Check Palindrome
A palindrome is a string or number that reads the same forward and backward.
This problem helps you understand string manipulation and logic building in Python.
1. Understanding the Problem
Given a string or number, check whether it is a palindrome.
Input: madam Output: Palindrome Input: hello Output: Not Palindrome
2. Method 1: Using String Slicing
s = input("Enter string: ")
if s == s[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
This is the simplest and most Pythonic way.
3. Method 2: Using Loop
s = input()
flag = True
for i in range(len(s)//2):
if s[i] != s[-i-1]:
flag = False
break
print("Palindrome" if flag else "Not Palindrome")
Compares characters from both ends.
4. Method 3: Using Function
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("racecar"))
Encapsulates logic for reuse.
5. Method 4: Palindrome Number
num = int(input())
original = num
rev = 0
while num > 0:
rev = rev * 10 + num % 10
num //= 10
print("Palindrome" if original == rev else "Not Palindrome")
Handles numeric palindrome checking.
6. Method 5: Handling Edge Cases
s = input().lower().replace(" ", "")
print("Palindrome" if s == s[::-1] else "Not Palindrome")
Ignores case and spaces.
7. Algorithm
1. Take input string/number.
2. Reverse it.
3. Compare with original.
4. If same → Palindrome.
5. Else → Not Palindrome.
8. Common Mistakes
1. Ignoring case sensitivity.
2. Not handling spaces.
3. Incorrect reversal logic.
4. Mixing string and number logic.
9. Applications
1. Text processing.
2. Data validation.
3. Competitive programming.
4. Interview problems.
Conclusion
Palindrome checking is a simple yet powerful problem for understanding string operations.
Python provides elegant solutions like slicing for quick implementation.
Codecrown