Louis Den Haan
Louis Den Haan

Reputation: 1

Determining if a word is a palindrome or not

My code to determine if a word is a palindrome or not is below.

word = str(input('Enter a word: '))
word = word.lower()
backwardsWord = word.lower()
for i in range(len(word) - 1, -1, -1)
    backwardsWord = backwardsWord + word[i]
    print(word + " in reverse is: " + backwardsWord)
    if backwardsWord == word:
        print("This word is a palindrome")
    elif backwardsWord != word:
        print("This word is not a palindrome")

When I run the program it spells the word out letter by letter and determines if the letter is the same as what was initially inputted. For example this is my output when I use the word radar:

radar in reverse is: r
This word is not a palindrome
radar in reverse is: ra
This word is not a palindrome
radar in reverse is: rad
This word is not a palindrome
radar in reverse is: rada
This word is not a palindrome
radar in reverse is: radar
This word is a palindrome

How would I be able to make it so that the output only outputs the last two lines and not the ones before it?

Upvotes: 0

Views: 81

Answers (2)

jf192210
jf192210

Reputation: 157

Put the if ... elif statement after the loop body

Upvotes: 0

SuperStormer
SuperStormer

Reputation: 5407

The loop is unnecessary:

word = str(input('Enter a word: '))
word = word.lower()
backwardsWord = word[::-1]
print(word + " in reverse is: " + backwardsWord)
if backwardsWord == word:
        print("This word is a palindrome")
elif backwardsWord != word:
    print("This word is not a palindrome")

If you prefer, you can also use backwardsWord = "".join(reversed(word)) if you think it is more clear.

If you still want to keep the explicit loop:

word = str(input('Enter a word: '))
word = word.lower()
backwardsWord = ""
for i in range(len(word) - 1, -1, -1):
    backwardsWord = backwardsWord + word[i]
print(word + " in reverse is: " + backwardsWord)
if backwardsWord == word:
    print("This word is a palindrome")
elif backwardsWord != word:
    print("This word is not a palindrome")

Upvotes: 3

Related Questions