In this program. you’ll learn how to check whether a given input string is a palindrome or not
A palindrome string is a word, phrase, or sequence of characters that reads the same forward and backward.
For example, the word “racecar” is a palindrome because it reads the same way in both directions.
Another example is the phrase “A man, a plan, a canal, Panama!” which is a palindrome because it reads the same forward and backward, even with the spaces and punctuation included.
Palindromes can also be numbers that are the same when you read them forwards and backward, like the number “121”. It’s like a secret code that you can figure out if you read it the right way!
Palindrome checking Using a For Loop
This example uses for loop to check whether a given input string is a palindrome or not.
The program asks for the user input to enter a string and then uses a for loop to iterate over the characters of the string and compare letters from the starting and ending sides.
string = input("Enter a string: ")
is_palindrome = True
for i in range(len(string)):
if string[i] != string[len(string)-i-1]:
is_palindrome = False
break
if is_palindrome:
print(string, "is a palindrome")
else:
print(string, "is not a palindrome")
Output
Enter a string: racecar
racecar is a palindrome
String Slicing method to check Palindrome
In this example, we use string slicing to check whether a given string is a palindrome or not. The program prompts the user to enter a string and then uses string slicing to create a new string that is the reverse of the original string.
The program then checks whether the original string is equal to the reversed string. If they are equal, then the string is a palindrome.
string = input("Enter a string: ")
reversed_string = string[::-1]
if string == reversed_string:
print(string, "is a palindrome")
else:
print(string, "is not a palindrome")
Output
Enter a string: racecar
racecar is a palindrome
Using Recursion to Check Palindrome
In this example we use a recursive function to check the palindrome of a string. A recursive function call itself over and over again util the condition is false
def is_palindrome(string):
if len(string) <= 1:
return True
elif string[0] != string[-1]:
return False
else:
return is_palindrome(string[1:-1])
string = input("Enter a string: ")
if is_palindrome(string):
print(string, "is a palindrome")
else:
print(string, "is not a palindrome")
Output
Enter a string: racecar
racecar is a palindrome
A recursive function is a type of function that repeatedly calls itself until a certain condition is met. In this case, the recursive function checks the string to determine if it’s a palindrome by breaking it down into smaller parts and comparing them.
The function keeps calling itself until it reaches the base case, where the string has been reduced to its smallest unit and can be compared with its mirror image.