我试图通过制作简单的程序来学习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循环中)。为什么没有为操作分配我输入的值以退出循环?
发布于 2020-05-20 19:24:25
你需要使用和代替或。如果满足任何条件,则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.")
发布于 2020-05-20 19:25:51
在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"]:
发布于 2020-05-20 19:27:37
您所做的测试永远不会返回False
,因为"b"
和"c"
都被视为“真实的”值,并且您在说“而动作不是OR ("b”或"c“是真的)--可能不是您想表达的。
您可以更准确地表示您的情况如下:
while action not in ("a", "b", "c"):
...
此外,dict
是一种很好的方法。您能想出一种方法将有效的命令和它们引起的响应都存储在字典中吗?
https://stackoverflow.com/questions/61921178
复制相似问题