这是我的代码,
if diff != "1" or diff != "2" or diff != "3":
print("You need to pick either 1, 2 or 3\n")
出于某种原因,结果是,
Pick a difficulty:
1) Easy
2) Medium
3) Hard
>> 2
You need to pick either 1, 2 or 3
我希望if语句检查变量 diff 是否等于字符串 1,2和3 。但是当我把 1,2或3 放入时,diff的错误信息不等于打印数字。为什么会这样?
答案 0 :(得分:2)
要应用“not any”逻辑,您需要检查它是否是任何有效结果然后反转。 (NOR)
if not (diff == "1" or diff == "2" or diff == "3"):
或者应用DeMorgan's theorem这对于“不等于1而不等于2而不等于3”是公平的
if diff != "1" and diff != "2" and diff != "3":
当然python还有in
和not in
运算符,这使得它更加清晰:
if diff not in ("1", "2", "3"):
答案 1 :(得分:0)
您需要使用而不是或。如果输入1,则diff != "1"
将返回True。
您的代码应如下所示:
if diff != "1" and diff != "2" and diff != "3":
print("You need to pick either 1, 2 or 3\n")