2016-10-06 17 views
0

ヤクシャーマット!私は、Pythonを使い捨てスクリプトを作成するJavaプログラマーです。私は下のコードに示されているパーサーを作りたいと思います。ブロックの条件が正しく動作しないのはなぜですか?

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

あなたのメッセージは、3異なる長さ5を、持っているので、ValueErrorが送出されます。代わりに 'size = 3とsize!= 5:'を使いたいのですか? –

+0

@ tommy.carstensen - とは何ですか:5の後に?サイズが3でない場合はメッセージを拒否したい5.なぜ私のニーズを満たすために「と」を使用するのかわからない –

+0

以下の@idjawからの明示的/精巧な答えを見てください。 –

答えて

3

あなたの問題はorを使用して、条件文である:

if size != 3 or size != 5: 

サイズは3に等しくない「OR」それは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 
代わり

は、さらに良いことに、not in

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

ありがとうございます。ダー!私は今、とても愚かな気がする。 –

1

構文的に使用

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 

andを使用し、何も問題ではありませんあなたのコード。あなたのコードに従って出力が正しいです。

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 
関連する問題