Introduction
A palindrome is a string that reads the same forward and backward. This tutorial will guide you through creating a Python program that checks whether a given string is a palindrome.
Example:
-
Input:
madam
-
Output:
madam is a palindrome
-
Input:
hello
-
Output:
hello is not a palindrome
Problem Statement
Create a Python program that:
- Takes a string as input.
- Checks if the string is a palindrome.
- Displays whether the string is a palindrome or not.
Solution Steps
- Take Input from the User: Use the
input()
function to get a string from the user. - Normalize the String: Convert the string to the same case (lowercase or uppercase) to ensure the check is case-insensitive.
- Reverse the String: Use slicing or another method to reverse the string.
- Compare the Original String with the Reversed String: If they are the same, the string is a palindrome.
- Display the Result: Use the
print()
function to display whether the string is a palindrome.
Python Program
# Python Program to Check if a String is Palindrome
# Author: https://www.rameshfadatare.com/
# Step 1: Take input from the user
input_string = input("Enter a string: ")
# Step 2: Normalize the string by converting it to lowercase
normalized_string = input_string.lower()
# Step 3: Reverse the string using slicing
reversed_string = normalized_string[::-1]
# Step 4: Compare the original string with the reversed string
if normalized_string == reversed_string:
print(f"{input_string} is a palindrome")
else:
print(f"{input_string} is not a palindrome")
Explanation
Step 1: Take Input from the User
- The
input()
function prompts the user to enter a string. The input is stored in the variableinput_string
.
Step 2: Normalize the String
- To make the palindrome check case-insensitive, the string is converted to lowercase using the
lower()
method.
Step 3: Reverse the String
- The string is reversed using slicing
[::-1]
. This creates a new string that is the reverse of the original.
Step 4: Compare the Original String with the Reversed String
- The program checks if the normalized string is equal to its reverse. If they are the same, the string is a palindrome.
Step 5: Display the Result
- The
print()
function is used to display whether the string is a palindrome or not.
Output Example
Example 1:
Enter a string: madam
madam is a palindrome
Example 2:
Enter a string: hello
hello is not a palindrome
Example 3:
Enter a string: RaceCar
RaceCar is a palindrome
Conclusion
This Python program demonstrates how to check whether a string is a palindrome by reversing the string and comparing it to the original. It handles case-insensitivity by normalizing the string to lowercase, ensuring that the check works correctly regardless of the input’s case. This example is helpful for beginners to understand string manipulation and comparison in Python.