Palindrome Program in Python
In this lesson: Check palindrome strings and numbers in Python using slicing and loops — code with output. Copy & run now. In Hindi & English.
What is a palindrome
A palindrome is a word, phrase or number that reads the same forwards and backwards — like "madam", "level" or 121. Checking one in Python is quick, and it is a great way to practise strings and comparisons.
The easy slicing way
word = "madam"
if word == word[::-1]:
print("Palindrome")
else:
print("Not a palindrome")
word[::-1] reverses the string. If the original equals its reverse, it is a palindrome. This one line is the simplest method.
Dry run
| Step | What | Value |
|---|---|---|
| 1 | word | "madam" |
| 2 | word[::-1] (reversed) | "madam" |
| 3 | Compare: word == word[::-1] | "madam" == "madam" → True → Palindrome! |
A palindrome reads the same both ways. In Python word[::-1] reverses the string. If forwards and backwards are equal, it is a palindrome. "madam" reversed is still "madam".
Checking with a loop
To see the logic, compare characters from both ends moving inward.
word = "level"
is_pal = True
n = len(word)
for i in range(n // 2):
if word[i] != word[n - 1 - i]:
is_pal = False
break
print("Palindrome" if is_pal else "Not")
We compare the first with the last, second with second-last, and so on — only up to the middle (n // 2). If any pair differs, it is not a palindrome.
Palindrome number
n = 121
if str(n) == str(n)[::-1]:
print("Palindrome number")
else:
print("Not")
The easiest way for numbers is to convert to a string and use the same slice check. 121 reversed is 121, so it is a palindrome.
Common mistakes
- Ignoring case for phrases. "Madam" vs "madaM" — lowercase first with
.lower(). - Not removing spaces in phrases. Strip spaces before comparing "nurses run".
- Looping the whole length. You only need to check up to
n // 2. - Comparing a number directly with slicing. Convert to a string first:
str(n)[::-1].
Summary
- A palindrome reads the same forwards and backwards.
- Easiest check:
word == word[::-1]. - A loop compares characters from both ends up to the middle.
- For numbers, use
str(n) == str(n)[::-1]. - For phrases, lowercase and remove spaces first.
Next, learn reversing in reverse a string or list, or try pattern programs.
Frequently Asked Questions
What is a palindrome?
What is the easiest way to check a palindrome in Python?
word == word[::-1]. If they are equal, it is a palindrome. This is the shortest and most Pythonic method.How do I check a palindrome without slicing?
How do I check if a number is a palindrome?
str(n) == str(n)[::-1]. Alternatively, reverse the number mathematically and compare it to the original.