Why are the conditions in if block not working correctly?
<p>Yakshemash ! I am a Java programmer learning python to make throwaway scripts. I want to make a parser which is shown in the code below.</p>

<pre><code>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)
</code></pre>

<p>This code throws the error:</p>

<pre><code>Traceback (most recent call last):
  File "/temp/file.py", line 9, in &lt;module&gt;
    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.
</code></pre>

<p>What is my mistake and how do I correct it ?</p>

<p>Your problem is with your conditional statement using <code>or</code>: </p>

<pre><code>if size != 3 or size != 5:
</code></pre>

<p>If the size is not equal to 3 "OR" it is not equal to 5, then raise. </p>

<p>So, with your input being passed: <code>12345</code></p>

<pre><code>Is it not equal to 3? True
Is it not equal to 5? False

True or False = True

Result: Enter condition and raise
</code></pre>

<p>Instead, use <code>and</code></p>

<pre><code>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
</code></pre>

<p>Even better, use <code>not in</code></p>

<pre><code>if size not in (3, 5):
</code></pre>

python