Booleans Add Up
This result suprised me today. If you add True to True in Python you get an integer 2 instead of a TypeError being raised. This is slightly unexpected but presumably there for backwards compatibility?
Python 2.4.4 (#2, Apr 5 2007, 20:11:18)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> True
True
>>> False
False
>>> True+False
1
>>> False+False
0
>>> True+True
2
on May 31st, 2007 at 9:11 pm
The two boolean constants True and False are defined to have the integer values 1 and 0 when used in a numerical context.
Many processors have represented false as the value zero. Many programming languages picked up on this and used integer zero as false and any other integer value as representing true. C does this and Pythons ideas of true and false are rooted in that, but with nobs on: http://docs.python.org/lib/truth.html, http://docs.python.org/lib/node34.html .
- Paddy.