有什么更好的我可以使用/导入?在Python中使用“不等于”的最佳方式是什么?
while StrLevel != "low" or "medium" or "high":
StrLevel = input("Please enter low, medium, or high for the program to work; ")
有什么更好的我可以使用/导入?在Python中使用“不等于”的最佳方式是什么?
while StrLevel != "low" or "medium" or "high":
StrLevel = input("Please enter low, medium, or high for the program to work; ")
事实上,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
表达'StrLevel =“低”或“中等”或“高”'可以更简明地写为'StrLevel =“低“或”中“。 –
你现在写的方式是无限循环,所以'虽然True'或'while 1'是一个更简单的方法来做到这一点...但我希望这不是你想要做的。 – kindall
可能的重复[如何测试一个变量对多个值?](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) –