user2407334 user2407334 - 1 year ago 34
Python Question

Is there any difference between bool() vs == in python truth testing?

I have two questions.

  1. Can ANYTHING (objects, types, operations, functions..) in python return a boolean value when it is called upon by the bool() method?

  2. Why dont the following two lines of code return the same answer?

    print (float == True) #prints False
    print bool(float) #prints True

Answer Source

The two, == and bool(), are different. == is for equality testing, whereas bool() returns the result of truth value testing for the object passed to it as parameter.

According to documentation of bool() -

class bool([x])

Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True.

The standard truth testing procedure can be found in the documentation -

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  1. None

  2. False

  3. zero of any numeric type, for example, 0, 0L, 0.0, 0j.

  4. any empty sequence, for example, '', (), [].

  5. any empty mapping, for example, {}.

  6. instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False.

All other values are considered True — so objects of many types are always true.

When you do bool(float), you are checking the truth value for float, which is True.

But when you do float == True, you are doing equality (please note this is not truth value testing, it is equality). In this case float and True are not equal so that results in False.