为什么if块中的条件不能正常工作?

时间:2016-10-06 02:33:59

标签: python

Yakshemash!我是一名Java程序员,学习python来制作一次性脚本。我想创建一个解析器,它显示在下面的代码中。

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.

我的错误是什么?如何纠正?

2 个答案:

答案 0 :(得分:3)

您的问题在于使用if size != 3 or size != 5: 的条件语句:

12345

如果尺寸不等于3&#34; OR&#34;它不等于5,然后加注。

因此,您的输入被传递: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):

<table id="users" class="table table-striped table-bordered nowrap" data-conf="@Model.ExtraVM.DialogMsg" data-title="@Model.ExtraVM.DialogTitle" data-btnok="@Model.ExtraVM.Button1" data-btncancel="@Model.ExtraVM.Button2">
                    <thead>
                        <tr>
                            <th>@Model.HeadingVM.Col1</th>
                            <th>@Model.HeadingVM.Col2</th>
                            <th>@Model.HeadingVM.Col3</th>
                            <th>@Model.HeadingVM.Col4</th>
                            <th>@Model.HeadingVM.Col5</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>

答案 1 :(得分: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.

由于上述条件始终会产生 true ,我认为您想要做其他事情。

现在将逻辑运算符设置如下:

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