Skip to content Skip to sidebar Skip to footer

Boolean Python Value Confusion

I'm new to Python and while trying Python logical statements.I came across this which I'm not able to understand.Can anyone tell me whats happening here in Python 2.7.Whats the dif

Solution 1:

You are being confused by the behaviour of the or operator; it returns the first expression that only if it is a true value; neither 0 nor False is true so the second value is returned:

>>> 0or'bar''bar'>>> Falseor'foo''foo'

Any value that is not numerical 0, an empty container, None or False is considered true (custom classes can alter that by implementing a __bool__ method (python 3), __nonzero__ (python 2) or __len__ (length 0 is empty).

The second expression is not even evaluated if the first is True:

>>> Trueor1 / 0True

The 1 / 0 expression would raise a ZeroDivision exception, but is not even evaluated by Python.

This is documented in the boolean operators documentation:

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

Similarly, and returns the first expression if it is False, otherwise the second expression is returned.

Solution 2:

The nature of this behavior is in python's order of expression evaluation. Python evaluates expressions from left to right, and it does it in a lazy manner. This means, that ones interpreter reaches the point, when the value of the expression is True, regardless of the rest of the expression, it will follow the branch of workflow, associated with the expression. If none of the expressions is True, it will simply return the most recent (last one). This gives the benefits of saving computational resources. Consider the following code:

>>>FalseorFalseorTrueorrange(10**8) 
True
>>>

Note, that range(10**8) is never called in this case, hence, a lot of time is saved.

Post a Comment for "Boolean Python Value Confusion"