有什麼更好的我可以使用/導入?在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) –