Palindrome programs are common beginner-level programming problems that help you understand strings, numbers, loops, conditions, and comparison operations. A palindrome is a value that remains the same when its characters or digits are read from left to right or right to left.
For example, "madam" is a palindrome because reversing it gives "madam" again. Similarly, 121 is a palindrome number because its reverse is also 121.
In Python, there are several ways to check whether a value is a palindrome. In this article, we will learn different approaches and understand how each program works.
Table of Contents
What is a Palindrome in Python?
A palindrome is a word, string, or number that reads the same forward and backward.
Examples:
Non-Palindrome Examples:madam → madamlevel → level121 → 1211331 → 1331
python → nohtyp
123 → 321
hello → olleh
If the original value and its reversed value are the same, the value is considered a palindrome.
Why Check for a Palindrome?
Checking for palindromes is a useful programming exercise because it combines several basic Python concepts.
- Improves Logical Thinking: Palindrome problems require you to compare an original value with its reverse.
- Practices String Manipulation: They provide practical experience with reversing and comparing strings.
- Helps Understand Conditions: An if-else statement is commonly used to determine whether a value is a palindrome.
- Provides Loop Practice: Palindromes can be checked using for and while loops, helping beginners understand iteration.
- Builds Problem-Solving Skills: The same problem can be solved using different approaches, helping you understand alternative programming techniques.
Palindrome Program Using String Slicing
One of the simplest ways to check whether a string is a palindrome is to reverse it using [::-1] and compare it with the original string.
Example:
# Python program to check whether a string is a palindrome
text = "madam"
# Reversing the string
reversed_text = text[::-1]
# Comparing the original and reversed strings
if text == reversed_text:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Output:
The string is a palindrome.
Explanation:
- The variable text stores "madam".
- text[::-1] reverses the string.
- The reversed string is stored in reversed_text.
- The if statement compares the original and reversed strings.
- Since both are the same, the program prints that the string is a palindrome.
Palindrome Program Using User Input
Instead of checking a fixed string, you can allow the user to enter a value.
Example:
# Python program to check a user-entered string for palindrome
text = input("Enter a string: ")
# Reversing the string
reversed_text = text[::-1]
# Checking whether the string is a palindrome
if text == reversed_text:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Example Output:
Enter a string: levelThe string is a palindrome.
Another Example Output:
Enter a string: pythonThe string is not a palindrome.
Explanation: The input() function takes a string from the user. The program then reverses the string using [::-1] and compares it with the original. If both are equal, the string is a palindrome.
Palindrome Program Using a for Loop
A palindrome can also be checked using a for loop. This approach is useful for understanding how characters can be processed individually.
Example:
# Python program to check a user-entered string for palindrome
text = input("Enter a string: ")
# Reversing the string
reversed_text = text[::-1]
# Checking whether the string is a palindrome
if text == reversed_text:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Output:
The string is a palindrome.
Explanation:
- The loop takes one character at a time and adds it to the beginning of reversed_text.
- For "madam":
- The final reversed string is "madam", which is the same as the original string. Therefore, it is a palindrome.
- m → m
- a → am
- d → dam
- a → adam
- m → madam
Palindrome Number Program
A palindrome can also be a number. For example, 121 remains 121 when its digits are reversed.
Example
# Python program to check whether a number is a palindrome
number = 121
# Converting the number into a string
text = str(number)
# Reversing the string
reversed_text = text[::-1]
# Comparing the original and reversed values
if text == reversed_text:
print("The number is a palindrome.")
else:
print("The number is not a palindrome.")
Output:
The number is a palindrome.
Explanation: The number 121 is first converted into a string using str(). This allows string slicing to be used. The reversed value is then compared with the original value.
Palindrome Number Using a while Loop
A number can also be reversed mathematically using a while loop without converting it into a string.
Example:
# Python program to check a palindrome number using a while loop
number = 121
original_number = number
reversed_number = 0
# Reversing the number digit by digit
while number > 0:
digit = number % 10
reversed_number = reversed_number * 10 + digit
number = number // 10
# Comparing the original and reversed numbers
if original_number == reversed_number:
print("The number is a palindrome.")
else:
print("The number is not a palindrome.")
Output:
The number is a palindrome.
Explanation:
- The program reverses the number one digit at a time.
- For 121: The last digit 1 is extracted.
- It is added to reversed_number.
- The last digit is removed from the original number.
- The process repeats until no digits remain.
- Finally, the reversed number is compared with the original number.
- Since both values are 121, the number is a palindrome.
Complete Palindrome Program
# Python program to check whether a user-entered value is a palindrome
text = input("Enter a word: ")
# Reversing the entered string
reversed_text = text[::-1]
# Checking whether the original and reversed strings are equal
if text == reversed_text:
print("Palindrome")
else:
print("Not a palindrome")
Example Output:
Enter a word: radarPalindrome
Explanation:
- text = input("Enter a word: "): The program takes a word from the user and stores it in the variable text.
- reversed_text = text[::-1]: The slicing expression [::-1] reverses the entered string.
- if text == reversed_text: The == operator checks whether the original string and reversed string are equal.
- print("Palindrome"): If both strings are equal, the program displays "Palindrome". Otherwise, the else block displays "Not a palindrome".
Common Mistakes to Avoid
1. Forgetting to Reverse the String: Simply comparing a string with itself will always return True. The original string must be compared with its reversed version, not with itself.
Wrong:# Python program with an incorrect palindrome checktext = "python"if text == text:print("Palindrome")
Correct:# Python program to correctly check a palindrometext = "python"if text == text[::-1]:print("Palindrome")else:print("Not a palindrome")
2. Forgetting That Uppercase and Lowercase Are Different: Python string comparisons are case-sensitive."Madam" and "madam" contain different cases. Converting the string to lowercase makes the comparison case-insensitive.
Wrong Expectation:
# Python program demonstrating case sensitivitytext = "Madam"if text == text[::-1]:print("Palindrome")else:print("Not a palindrome")Output:Not a palindrome
Correct:# Python program to check a palindrome without considering letter casetext = "Madam# Converting the string to lowercasetext = text.lower()if text == text[::-1]:print("Palindrome")else:print("Not a palindrome")Output:Palindrome
3. Forgetting to Store the Original Number: When reversing a number using a while loop, the original value is changed during the process. The original number should be stored in another variable before it is modified.
Wrong:# Python program with an incorrect number comparisonnumber = 121reversed_number = 0while number > 0:digit = number % 10reversed_number = reversed_number * 10 + digitnumber = number // 10if number == reversed_number:print("Palindrome")
Correct:# Python program to correctly check a palindrome numbernumber = 121original_number = numberreversed_number = 0while number > 0:digit = number % 10reversed_number = reversed_number * 10 + digitnumber = number // 10if original_number == reversed_number:print("Palindrome")else:print("Not a palindrome")
4. Forgetting to Convert a Number to a String: String slicing can only be applied to sequences such as strings, not directly to integers. The str() function converts the integer into a string, allowing slicing to be used.
Wrong:# Python program with incorrect slicing of an integernumber = 121print(number[::-1])Correct:# Python program to reverse a number using string conversionnumber = 121# Converting the number to a stringtext = str(number)print(text[::-1])
5. Ignoring Spaces and Special Characters: When checking phrases, spaces and special characters can affect the comparison.
For example, "nurses run" is a palindrome when spaces are ignored, but a direct comparison includes the space.
Correct Approach:# Python program to check a phrase as a palindrometext = "nurses run"# Removing spaces and converting to lowercasetext = text.replace(" ", "").lower()# Checking the palindromeif text == text[::-1]:print("Palindrome")else:print("Not a palindrome")Output:Palindrome
Conclusion
A palindrome program is a useful beginner-level Python problem that combines strings, numbers, loops, conditions, comparison operators, and string manipulation. The basic idea is simple: reverse a value and compare the reversed result with the original.
Python provides several ways to solve this problem. String slicing with [::-1] is the simplest approach, while for and while loops provide a better understanding of how the reversal process works internally. Palindrome programs are excellent practice for developing logical thinking and building a foundation for more advanced programming problems. :::
Frequently Asked Questions (FAQs)
1. What is a palindrome?
A palindrome is a word, string, number, or sequence that remains the same when read forward and backward.
2. How can I check a palindrome in Python?
One of the simplest methods is to reverse the string using [::-1] and compare it with the original string.
3. Can numbers be palindromes?
Yes. Numbers such as 121, 1331, and 1221 are palindrome numbers because their digits remain the same when reversed.
4. Can I check a palindrome using a loop?
Yes. You can use either a for loop or a while loop to reverse or compare the characters or digits.
5. Are palindrome checks case-sensitive?
Normal string comparisons are case-sensitive. For example, "Madam" and "madam" are considered different. You can use .lower() or .upper() when you want to ignore case.
6. Can a phrase be a palindrome?
Yes. Some phrases can be palindromes when spaces, punctuation, and capitalization are ignored. The program must remove or normalize these characters before checking.
0 Comments