DEV Community

Adhi sankar
Adhi sankar

Posted on

How to Check a Palindrome in Python

A palindrome is a word, number, or sentence that reads the same forward and backward.

For example:

  • madammadam
  • levellevel
  • 121121
  • racecarracecar

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")
Enter fullscreen mode Exit fullscreen mode

How Does the Program Work?

1. Get input from the user

word = input("Enter a word: ")
Enter fullscreen mode Exit fullscreen mode

This asks the user to enter a word.

For example:

Enter a word: madam
Enter fullscreen mode Exit fullscreen mode

2. Reverse the word

reverse = word[::-1]
Enter fullscreen mode Exit fullscreen mode

[::-1] is used to reverse a string.

For example:

madam → madam
hello → olleh
Enter fullscreen mode Exit fullscreen mode

3. Compare the original and reversed words

if word == reverse:
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

If the word is a palindrome, the program prints:

It is a palindrome
Enter fullscreen mode Exit fullscreen mode

Otherwise:

It is not a palindrome
Enter fullscreen mode Exit fullscreen mode

Example

Input

Enter a word: level
Enter fullscreen mode Exit fullscreen mode

Output

It is a palindrome
Enter fullscreen mode Exit fullscreen mode

Another example:

Input

Enter a word: python
Enter fullscreen mode Exit fullscreen mode

Output

It is not a palindrome
Enter fullscreen mode Exit fullscreen mode

Conclusion

Checking a palindrome is a simple and useful Python exercise. It helps beginners understand:

  • Strings
  • User input
  • String slicing
  • if-else conditions
  • Comparing values

Top comments (0)