mardi 15 juin 2021

Working of the interpreter in this program

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.

Aucun commentaire:

Enregistrer un commentaire