2016-04-14 28 views
1

有什么更好的我可以使用/导入?在Python中使用“不等于”的最佳方式是什么?

while StrLevel != "low" or "medium" or "high": 
     StrLevel = input("Please enter low, medium, or high for the program to work; ") 
+0

表达'StrLevel =“低”或“中等”或“高”'可以更简明地写为'StrLevel =“低“或”中“。 –

+0

你现在写的方式是无限循环,所以'虽然True'或'while 1'是一个更简单的方法来做到这一点...但我希望这不是你想要做的。 – kindall

+0

可能的重复[如何测试一个变量对多个值?](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) –

回答

6

您可以使用not in

while strLevel not in ["low", "medium", "high"]: 
+0

好吧欢呼声,将在9分钟内或者无论它说我可以做到这一点在这个答案。 “你可以在9分钟内接受这个答案” – Mitchell

+0

@Mitchell这是“答案”fyi。我不确定字节码是如何反汇编的(即它可能在每个循环中实例化列表)。您可以使用'dis'模块查找,如果效率很高,最好在循环之前将选项存储为变量。 –

+0

@JaredGoguen好的,谢谢:) – Mitchell

0

事实上,not in建议

但什么意思你在问题中表现出的比较?

>>> StrLevel = 'high' 
>>> StrLevel != "low" or "medium" or "high" 
True 
>>> StrLevel = 'medium' 
>>> StrLevel != "low" or "medium" or "high" 
True 
>>> StrLevel = 'low' 
>>> StrLevel != "low" or "medium" or "high" 
'medium' 

...可能根本不符合您的预期。

为了简化了一点:

>>> 'foo' != 'bar' or 'medium' 
True 
>>> 'foo' != 'foo' or 'medium' 
'medium' 
>>> False or 'medium' 
'medium' 

这是一个有点混乱,如果你没有在Python之前来到语言用于布尔代数表达式。特别是因为Python去的麻烦,使算术比较有意义的链接时:!

>>> x = 12 
>>> 10 < x < 14 
True 
>>> 10 < x < 11 
False 
相关问题