3 common mistakes with “if” what might suprise you on python

most people just write python as it is writing a cake recipe, but it isin’t like that, today we will talk about the common mistakes with python if statements.

1- something is not … and is not …

this is a huge problem, since python we can both use != and “is not”, people normally get confused with it and thinks “and” will get the first something from the first statement, but it will not, what will happens is:

print("apple" is not "pineapple" and not "corn") # will print False!

#but...
print("apple" is not "pineapple" and "apple" is not "corn") # will print True!

obviusly i dont recommend using “is not” for these cases, normally just use “!=” stead, so it gives a error in these sintax mistakes, stead of proceeding with a warning.

2- var == none vs var is none

in this case, there is a long discussion on the internet, but actually the problem is very simple, if the return of a function have “__eq__”, where it defines how some stuff are compared inside a funcion it just makes var == none very hard to track, sometimes returning true and others false for example:

class class_fun(object):
    def __eq__(self,other):
        return not other

thing = class_fun()
print (thing == None)    #True
print (thing is None)    #False

this function is not very usefull but In this case, the __eq__ method returns the opposite of the other object, which is a boolean value. This means that an instance of this class will be equal to any object that evaluates to False, such as None, 0, “”, [], etc. Also it will not be equal to any object that evaluates to True, such as 1, “a”, [1, 2, 3], etc.

A more common and sensible way of defining the __eq__ method is to compare the attributes of the objects that are relevant for equality, such as their names, ids, values, etc. For example, if you have a class that represents a person, you may want to compare their names and ages for equality.

But anyway, a bad coded or infortunate cause can lead to this issue, so allways use “is” stead of “==” because is will look in a more profound way than “==” wich uses __eq__ function of each class.

3- Not using x > y > z (chained comparison)

this expression is pretty cool! actually can short out the code, stead of writting x > y and x > z, you can do something like y < x > z like so:

# old school method
if x > y and x > z:
     # ...

# cool method
if y < x > z:
     # ...

# other example, but with bool
if foo is True is bar: # or just use ==
     # ...

Leave a Comment