Borat Sagdiyev Borat Sagdiyev - 2 months ago 6
Python Question

Why are the conditions in if block not working correctly?

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.

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)


This code throws the error:

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.


What is my mistake and how do I correct it ?

Answer

Your problem is with your conditional statement using or:

if size != 3 or size != 5:

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

So, with your input being passed: 12345

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

True or False = True

Result: Enter condition and raise

Instead, use 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

Even better, use not in

if size not in (3, 5):