Search code examples
pythonfor-looppalindrome

Checking for a palindrome, using for-loop in Python and print output ONLY ONCE


I am fairly new to programming, so I hope you can help me.

I want to check if a input string is a palindrome. The palindrome-checker is case-insensitive.

Here is what I got so far:

# input word 
word = input("Enter a word: ")

# make it case-INsensitive
word = word.lower()

# we also need the length of word to iterate over its range
length_word = int(len(word))

### use a for-loop
for letter in range(len(word)):
    if word[-length_word] == word[-1]:
        print(word, "is a palindrome.")     
        
# if it doesn't match, its not a palindrome, print message
    else:
        print(word, "is not a palindrome.")

What bothers me is that it prints the phrase "is a palindrome." everytime. How can I fix it so it will only print it once if the word is a palindrome?

Thank you so much in advance!


Solution

  • You just need to check the word against it's reverse:

    # input word 
    word = input("Enter a word: ")
    
    # make it case-INsensitive
    word = word.lower()
    
    # check word against it's reverse
    if word == word[::-1]:
        print(word, "is a palindrome")
    else:
        print(word, "is not a palindrome")