Exercise 24

A palindrome is a word whose order of letters remains the same whether it is read from left to right or from right to left. For example: 'laval', 'radar,' sos' ... are palindromes.
Write a program in Python that asks the user to enter a word and return it if it is a palindrome or not?

Solution

First method:

word = input("Enter a word: ")

# Reverse the word and compare it with the original
if word == word[::-1]:
    print(f"{word} is a palindrome")
else:
    print(f"{word} is not a palindrome")

Explanation:

  1. The input() function: prompts the user to enter a word and stores it in the word variable.
  2. The [: -1] slicing syntax: is used to reverse the string.
  3. The if statement: checks if the reversed string is the same as the original string. If it is, then the word is a palindrome.
  4. If the word is a palindrome: the program prints a message saying so.
  5. Otherwise: it prints a message saying the word is not a palindrome.





Second method:
Can we solve this problem without slicing the word?
Certainly! Here's an alternate method to check if a word is a palindrome or not in Python, without using string slicing:

word = input("Enter a word: ")

is_palindrome = True

# Loop through the word and compare characters from both ends
for i in range(len(word)//2):
    if word[i] != word[-i-1]:
        is_palindrome = False
        break

if is_palindrome:
    print(f"{word} is a palindrome")
else:
    print(f"{word} is not a palindrome")

Explanation:

  1. The input() function: prompts the user to enter a word and stores it in the word variable.
  2. We use boolean variable is_palindrome: initialized as True.
  3. We loop through the word: using a for loop and compare the characters from both ends of the word. We use len(word)//2 as the range for the loop because we only need to check half the length of the word.
  4. If any character from the beginning: of the word does not match its corresponding character from the end of the word, we set is_palindrome to False and break out of the loop.
  5. Finally: we check the value of is_palindrome. If it is True, then the word is a palindrome. Otherwise, it is not. We print a message accordingly.

 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 24: python program to check whether a word is palindrome or not”

Leave a Reply