2016-04-01 73 views
0

使用多個邏輯運算符,我有點好奇,如果有什麼東西,我在下面的代碼丟失,在python

我希望用戶輸入的邏輯或者"Y""H""E",我想使用return聲明轉移到另一個班級。否則,我使用else部分返回布爾值False

有一個while循環會將控制權發送回相同的功能,直到用戶輸入所需的值。

在運行程序時,無論接收到什麼輸入,它都不會進入else部件。

def getUserIngameOption(self): 

    userIngameOption=raw_input("Please Enter Y -> for Turn | H -> Hint | E -> to End")   
    userDesc=userIngameOption.upper() 


    if not (userDesc==("Y") or ("H") or ("E")): 

     print "Mate PLEASE JUST TYPE WHATTTT is asked for !! not this",userDesc 
     return False 
    else: 
     self.userOpt=userDesc 
     print "This is detail that you got>>>",self.userOpt 
     return self.userOpt 
+2

原標題對這一問題的 「Python中使用多個位運算符」。就像註釋一樣,這是一個**邏輯**'或',而不是**按位**'或'。 –

回答

1

發生的事情是每個人都被單獨評估,您需要明確比較每個值。

if not (userDesc=="Y" or userDesc=="H" or userDesc=="E") 

在您當前的代碼中,「E」和「H」將評估爲True。

1

更改該行:

if not (userDesc==("Y") or ("H") or ("E")): 

到:

if not (userDesc == "Y" or userDesc == "H" or userDesc == "E"): 

應該做的伎倆。

你也可以做到以下幾點:

if not userDesc in ("Y", "H", "E"): 

這將考驗userDesc是否是這三個值中的一個。

4

您沒有正確進行比較。您將第一次比較的結果與「H」和「E」的布爾值進行或運算。由於'H'和'E'的布爾值爲True,因此IF語句將始終爲False(因爲您正在將條件的結果反轉爲not)。

更改此:

if not (userDesc==("Y") or ("H") or ("E")) 

到:

if userDesc not in ("Y","H","E"): 
0

如果不是(userDesc ==( 「Y」)或( 「H」)或( 「E」))的裝置(userDesc ==(「Y」))或((「H」))或((「E」)),第二和第三項始終爲真。

1

這個正確的方法:

if not (userDesc=="Y" or userDesc=="H" or userDesc=="E") 

或本:

if userDesc not in ("H","Y","E").