簡體   English   中英

Python 2-如何使用“或”?

[英]Python 2 - How do I use 'or'?

我真的是python新手,並且我剛剛編寫了一個小程序。 如果鍵入“ Hello”或“ hello”,它將顯示為“正在工作”,如果鍵入其他任何內容,則將顯示為“不工作”。 這是我到目前為止的代碼:

print "Type in 'Hello'"
typed = raw_input("> ")
if (typed) == "Hello" or "hello":
   print "Working"
else:
    print "not working"

該代碼不起作用,無論我提交什么內容,即使我鍵入“ jsdfhsdkfsdhjk”,它也始終會顯示“正在工作”。 如果我取出“ or”和“ hello”,它確實可以工作,但是我想同時檢查兩者。 如何使腳本起作用?

非常感謝!!

您正在檢查typed是否等於"Hello"或者作為獨立表達式的"hello"計算結果是否為true(確實如此)。 您不必鏈接多個值來檢查原始變量。 如果要檢查一個表達式是否等於不同的事物,則必須重復它:

if typed == 'Hello' or typed == 'hello':

或者,類似:

if typed in ['Hello', 'hello']: # check if typed exists in array

或者,是這樣的:

if typed.lower() == 'hello': # now this is case insensitive.

if (typed) == "Hello" or "hello":應該是if typed == "Hello" or typed == "hello":

目前的問題是or應該分開兩個問題。 它不能用於將同一問題的兩個答案分開(我認為這是您期望的結果)。

因此,python嘗試將“ hello”解釋為一個問題,並將其強制轉換為true / false值。 碰巧“ hello”強制轉換為true (您可以查找原因)。 因此,您的代碼實際上說的是“ if something or TRUE”,始終為true ,因此始終輸出“ working”。

您可能要嘗試將typed轉換為小寫,因此只需檢查一件事。 如果他們鍵入“ HELLO”怎么辦?

typed = raw_input("> ")
if typed.lower() == "hello":
    print "Working"
else:
    print "not working"

or (和and )兩側的表達式彼此獨立地求值。 因此,右側的表達式不會共享左側的'=='。

如果您想針對多種可能性進行測試,則可以

typed == 'Hello' or typed == 'hello'

(如Hbcdev所建議),或使用in運算符:

typed in ('Hello', 'hello')

您可以通過兩種方式做到這一點(Atleast)

print "Type in 'Hello'"
typed = raw_input("> ")
if typed == "Hello" or typed == "hello":
   print "Working"
else:
    print "not working"

或者使用in

print "Type in 'Hello'"
typed = raw_input("> ")
if typed in ("Hello","hello",):
   print "Working"
else:
    print "not working"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM