首页 > 解决方案 > 解释器在这个程序中的工作

问题描述

这听起来像是一个愚蠢的问题,但我不得不问。以下代码检查用户输入的单词是否为回文。当我使用下面的代码时,它对所有单词都说“这个词是回文”。

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.")

但是当我在下一个代码块中做这个小改动时,它会正确地检测到这个词是否是回文。我在反复试验的基础上得到了这个。

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.")

请帮忙。提前致谢。

标签: python-3.xif-statementjupyter-notebookinterpreterpalindrome

解决方案


目前,一些问题是您的“最终”答案基于“最后”测试。你真正想做的是,一旦你确定了,就说“不是回文”,然后停下来。

尝试:

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

还要注意,这在技术上可以简化为:

is_a_palindrome = word == "".join(reversed(word))

推荐阅读