如何解决while循环中的逻辑错误?

时间:2017-10-26 19:13:53

标签: python while-loop

StackOverFlow的程序员,我是一名研究Python的少年,我无法在我的一个代码中找到逻辑错误。我希望你能帮忙。 我有两个逻辑错误。  1.如果答案是"是"或"不"它不断打开while命令。  2.从第一个错误得出结论,当选择=="是"时,它永远不会停止。或"不" ..

我的编码在这里:

choice = raw_input("Do you like programming? (yes/no) : ")
while choice != "yes" or "no":
    choice = raw_input('Come on, answer with a "yes" or with a "no" ! : ') 
if choice == "yes":
    print "I like you !"
elif choice == "no":
    print "I am sorry to hear that .. "

,提前谢谢!

2 个答案:

答案 0 :(得分:0)

这是问题所在:

while choice != "yes" or "no":

这被Python解释为(choice != "yes") or ("no")。由于"no"是一个非零长度的字符串,因此它是真实的。这使得or表达式为true,因为任何OR true都为真。所以你的情况总是正确的,循环永远不会停止。

应该是:

while choice != "yes" and choice != "no":

或者:

while choice not in ("yes", "no"):

答案 1 :(得分:0)

第二行评估为True。因为字符串" no"评估为真

尝试以下

if "any string": print(1) #will always print 1, unless the string is empty

你应该使用的是

while choice not in ["yes", "no"]:

检查choice是否与"yes""no"匹配

相关问题