Bolean... puzzled!


Hello everyone,

Boolean = not not True or False and not True
is it False or True?

PS: I stated False but the answser was True… why?

Thank you for your help!


to get to this solution, we need to understand the order in which this operators are evaluated:

just like maths operators the python operators are not evaluated from left to right

so first you have to evaluate all the not keywords, which results in:

True or False and False

then we have to evaluate False and False, and finally we have to compare True or (result of False and False)

Which result in?

How did you get to False?


or is short-circuited though, so the right side isn’t evaluated at all

for example:

>>> True or [][5]  # obviously out of bounds, but not evaluated


That’s a great concise demonstration of short-circuiting, @ionatan :smiley:

>>> True or [][5]
>>> False or [][5]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    False or [][5]
IndexError: list index out of range
>>> True and [][5]
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    True and [][5]
IndexError: list index out of range
>>> False and [][5]


Ok Thanks!

I didn’t know about the order of evaluation.
I thought you only put operations in () to indicate their priority…


In this case it does end up being left-to-right though (close enough anyway)

If python read everything from left-to-right there would be a LOT of parentheses in code… And some languages take this to an extreme, google lisp if you dare…those programs have a tendency to end in )))))))))))
You can use parentheses to override the default order, again, same as in grade-school math

Generally we try to write things so that there’s no doubt what the order is. But same as with math, you should know to do multiplication before addition.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.