2016-10-06 41 views
0

Yakshemash!我是一名Java程序員,學習python來製作一次性腳本。我想製作一個解析器,它顯示在下面的代碼中。爲什麼if塊中的條件無法正常工作?

class Parser(object): 
    def parse_message(self, message): 
     size= len(message) 
     if size != 3 or size != 5: 
      raise ValueError("Message length is not valid.") 

parser = Parser() 
message = "12345" 
parser.parse_message(message) 

此代碼引發錯誤:

Traceback (most recent call last): 
    File "/temp/file.py", line 9, in <module> 
    parser.parse_message(message) 
    File "/temp/file.py", line 5, in parse_message 
    raise ValueError("Message length is not valid.") 
ValueError: Message length is not valid. 

什麼是我的錯誤,我該如何改正呢?

+0

你的消息具有長度5,這與3個不同的,所以ValueError被掛起。你想要'如果size!= 3和size!= 5:'而不是? –

+0

@ tommy.carstensen - 什麼是:5之後?我想拒絕一個消息,如果它的大小不是3或不是5。不知道爲什麼會用「和」來滿足我的需求。 –

+0

請參閱下面@idjaw的明確/詳細答案。 –

回答

3

你的問題是使用or您的條件語句:

if size != 3 or size != 5: 

如果大小不等於3「或」這不是等於5,然後提高。

所以,隨着您的輸入被傳遞:12345

Is it not equal to 3? True 
Is it not equal to 5? False 

True or False = True 

Result: Enter condition and raise 

相反,使用and

if size != 3 and size != 5: 

Is it not equal to 3? True 
Is it not equal to 5? False 

True and False = False 

Result: Do not enter condition 

更妙的是,使用not in

if size not in (3, 5): 
+0

謝謝。杜!我現在覺得很愚蠢。 –

1

在語法上,有什麼錯你的代碼。根據你的代碼輸出是正確的。

size != 3 or size != 5: 
# This will be always *true* because it is impossible for **message** 
    to be of two different lengths at the same time to make the condition false. 

由於上述條件總是導致真正,我假設你想別人做一些事情。

現在把一個邏輯運算器的工作原理是以下:

size != 3 and size != 5: 
# This will be true if the length of **message** is neither 3 nor 5 
# This will be false if the length of **message** is either 3 or 5 
相關問題