Common mistakes we make in Python and why we should avoid that part 5

Posted by Afsal on Oct. 1, 2021, 3:29 a.m.

Hi Pythonistas!

This is part 5 of the common mistakes series. Today we are going to discuss a mistake that will make us scratch our heads.

Chaining the operator without undestanding it's working

5>4 == True

When we see this code, we will expect the answer to be True. But when we run the code, we can see that the result is the opposite of what we expected,i.e., False.

Why:

In Python, chaining works like this: 

The command 5>4 == True is equivalent to  5>4 and 4== True.

For 5 is greater than 4, the result is True. But 4== True is False

The result of True and False is always False. That's why our result became False.

Solution

(5>4) == True

The output of this expression will be True

 

When there are chaining expressions, always make sure that you need to use a bracket or not to get the proper output.

The links for the previous posts in this series are:

https://parseltongue.co.in/common-mistakes-we-make-in-python-and-why-we-should-avoid-that-part-4/

https://parseltongue.co.in/common-mistakes-we-make-in-python-and-why-we-should-avoid-that-part-3/

https://parseltongue.co.in/common-mistakes-we-make-in-python-and-why-we-should-avoid-that-part-2/

https://parseltongue.co.in/common-mistakes-we-make-in-python-and-why-we-should-avoid-that/