WARNING: This page is archived and not updated. Please bear in mind any information may be incorrect and any code may not work. Use at your own risk.
James Gardner: Home > Blog > 2007 > Booleans Add Up

Booleans Add Up

Posted:2007-05-31 17:20
Tags:Python

This result surprised 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

Comments

Paddy3118

Posted:2007-05-31 21:11

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.

URL:http://paddy3118.blogspot.com

(view source)

James Gardner: Home > Blog > 2007 > Booleans Add Up