How to Check a Palindrome in Python
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…
A palindrome is a word, number, or sentence that reads the same forward and backward. Common examples include madam, level, 121, and racecar. In this article, we will explore how to determine if a word is a palindrome using Python.
To begin, we prompt the user to enter a word. The Python command input() is used to collect the user's input. For instance, if the user types "madam", the variable word will store the value "madam".
Next, we reverse the entered word. This is achieved by utilizing Python's string slicing functionality with the syntax word[::-1]. In our example, "madam" will become "madam" again after reversal, while "hello" becomes "olleh".
We then compare the original word with the reversed word using an if-else statement. If both values are identical, the program concludes that the word is a palindrome. Conversely, if the words differ, the word is not a palindrome.
The program outputs the result accordingly. If the word is a palindrome, it prints "It is a palindrome". Otherwise, it displays "It is not a palindrome".
To illustrate, if the user inputs "level", the output will be "It is a palindrome". On the other hand, entering "python" will result in the output "It is not a palindrome".
In summary, checking for palindromes is an easy yet valuable exercise in Python programming. It introduces beginners to fundamental concepts such as strings, user input, string slicing, if-else conditions, and value comparison.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.