满足指定条件后,Python while循环不会结束

时间:2020-05-20 19:18:07

标签: python loops

我正在尝试通过编写简单的程序来学习Python。我的一个想法是创建一个只要不满足条件就循环的程序。这是代码:


print("What would you like to do?")
action = input("a. eat it   b. cook it  c. toss it\n>").lower()
while action != "a" or "b" or "c":
    print("That is not one of your options.")
    action = input(">")
if action == "a":
    print("You eat it.")
elif action == "b":
    print("You cook it.")
elif action == "c":
    print("You throw it away.")

只要不输入a,b或c,就应该继续循环并增加响应。问题是,即使我输入了a,b或c,它仍然告诉我它不是选项之一(也就是说,即使退出条件似乎已得到满足,它仍保留在while循环中。)为什么没有为操作分配我输入的值以退出循环?

3 个答案:

答案 0 :(得分:1)

您需要使用和代替or。如果满足任何条件,则or运算符求值为true。因此,如果您选择a,它仍然是正确的,因为它不是b或c。

尝试一下:

print("What would you like to do?")
action = input("a. eat it   b. cook it  c. toss it\n>").lower()
while action != "a" and action!= "b" and action!="c":
    print("That is not one of your options.")
    action = input(">")
if action == "a":
    print("You eat it.")
elif action == "b":
    print("You cook it.")
elif action == "c":
    print("You throw it away.")

答案 1 :(得分:0)

action != "a" or "b" or "c":循环中创建条件while的方式将始终为True。由于"b""c"将被评估为True

您需要按以下方式更改条件,并且还需要用or替换and

action != "a" and action != "b" and action != "c":

另一种方法是:

"abc".find(action) != -1 and len(action) == 1:

另一种方法可以是:

action not in ["a", "b", "c"]:

答案 2 :(得分:0)

您正在执行的测试永远不会返回False,因为"b""c"都被视为“真实的”值,并且您说的是“行动不是一个OR(“ b”或“ c”为真)”-可能不是您要表达的内容。

您可以通过以下方式更准确地表达自己的状况:

while action not in ("a", "b", "c"):
    ...

此外,dict是一种很好的方法。您能想到一种在字典中存储有效命令和它们引起的响应的方法吗?