2016-04-14 54 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 
相關問題