-1

This may sound like a stupid question but I had to ask. The following code checks whether a word entered by the user is a palindrome or not. When I use the below code, it says "This word is a Palindrome" for all the words.

word = input("Enter a word for a Palindrome : ")
word = word.replace(" ","")
k = -1
b = False

for i in range(0,len(word)):
    if word[i] == word[k]:
        k-=1
        b=True
    else:
        b=False
    
        
if b:
    print("The word is a Palindrome.")
else:
    print("The word is not a Palindrome.")

But when I do this small change in the next block of code, it correctly detects whether the word is palindrome or not. I got this in a trial and error basis.

word = input("Enter a word for a Palindrome : ")
word = word.replace(" ","")
k = -1
b = False

for i in range(0,len(word)):
    if word[i] == word[k]:
        b=True
    else:
        b=False
    k-=1
        
if b:
    print("The word is a Palindrome.")
else:
    print("The word is not a Palindrome.")

Please help. Thanks in advance.

Nishanth Nair
  • 17
  • 1
  • 4

1 Answers1

0

At the moment, some of the issue is that your "final" answer is based on the "last" test. What you really want to do is say "Not a Palindrome" as soon as you determine that and then stop.

Try:

is_a_palindrome = True
for index in range(len(word)):
    if word[index] != word[- (index+1)]:
        is_a_palindrome = False
        break

Note as well, that this can be technically simplified to:

is_a_palindrome = word == "".join(reversed(word))
JonSG
  • 10,542
  • 2
  • 25
  • 36