True evaluates to 1, and False evaluates to 0.
>>> True is 1 False >>> True == 1 True >>>
Bool is a subclass of int. As indicated in PEP-285 :
6) Should bool inherit from int?
=> Yes.
In an ideal world, bool could be better implemented as a separate integer type that knows how to perform mixed arithmetic. However, bool inheritance completely excludes the implementation (in part, since all C code that calls PyInt_Check () will continue to work - this returns true for subclasses of int). In addition, I think this is correct in terms of interchangeability: code that requires an int can be loaded by bool, and it will behave the same as 0 or 1. Code that requires bool to not work when it is given an int; for example, 3 & 4 is 0, but both 3 and 4 are true if we count the truth values.
This is not very practical, and there are other answers with sudo
examples of using bools. I thought it would be nice to have some real examples:
f,b="Fizz","Buzz" print "\n".join([["",f,b,f+b][(x%3==0) + 2*(x%5==0)] or str(x) for x in range(1,101)])
This section:
["",f,b,f+b][(x%3==0) + 2*(x%5==0)]
The choice of returning each line is based on two Boolean expressions, if both of them are true, we get (True) + 2*(True)
, which evaluates to 4, which is fizzbuzz. It's not too hard to understand once you get used to the idea that True == 1
and False == 0
Further compliance with the topic:
print '\n'.join(['Fizz'*(not i%3) + 'Buzz'*(not i%5) or str(i) for i in range(1, 101)])
This example is based on what happens when string multiplying by python:
>>> "Noelkd" * False ''
And that does not evaluate True 0:
>>> not True == 0 True
Used for this fall into two categories: