A palindrome is a word, number, or sentence that reads the same forward and backward.
For example:
-
madam→madam -
level→level -
121→121 -
racecar→racecar
In this blog, we will learn how to check whether a word is a palindrome using Python.
Python Program
word = input("Enter a word: ")
reverse = word[::-1]
if word == reverse:
print("It is a palindrome")
else:
print("It is not a palindrome")
How Does the Program Work?
1. Get input from the user
word = input("Enter a word: ")
This asks the user to enter a word.
For example:
Enter a word: madam
2. Reverse the word
reverse = word[::-1]
[::-1] is used to reverse a string.
For example:
madam → madam
hello → olleh
3. Compare the original and reversed words
if word == reverse:
The program checks whether the original word and reversed word are the same.
If they are the same, it is a palindrome.
4. Print the result
print("It is a palindrome")
If the word is a palindrome, the program prints:
It is a palindrome
Otherwise:
It is not a palindrome
Example
Input
Enter a word: level
Output
It is a palindrome
Another example:
Input
Enter a word: python
Output
It is not a palindrome
Conclusion
Checking a palindrome is a simple and useful Python exercise. It helps beginners understand:
- Strings
- User input
- String slicing
-
if-elseconditions - Comparing values
Top comments (0)