Josh Hunt
Josh Hunt

Reputation: 14511

Why does concatenating a boolean value return an integer?

In python, you can concatenate boolean values, and it would return an integer. Example:

>>> True
True
>>> True + True
2
>>> True + False
1
>>> True + True + True
3
>>> True + True + False
2
>>> False + False
0

Why? Why does this make sense?

I understand that True is often represented as 1, whereas False is represented as 0, but that still does not explain how adding two values together of the same type returns a completely different type.

Upvotes: 7

Views: 1011

Answers (3)

YOU
YOU

Reputation: 123791

Because In Python, bool is the subclass/subtype of int.

>>> issubclass(bool,int)
True

Update:

From boolobject.c

/* Boolean type, a subtype of int */

/* We need to define bool_print to override int_print */
bool_print
    fputs(self->ob_ival == 0 ? "False" : "True", fp);

/* We define bool_repr to return "False" or "True" */
bool_repr
    ...

/* We define bool_new to always return either Py_True or Py_False */
    ...

// Arithmetic methods -- only so we can override &, |, ^
bool_as_number
    bool_and,       /* nb_and */
    bool_xor,       /* nb_xor */
    bool_or,        /* nb_or */

PyBool_Type
    "bool",
    sizeof(PyIntObject),
    (printfunc)bool_print,          /* tp_print */
    (reprfunc)bool_repr,            /* tp_repr */
    &bool_as_number,                /* tp_as_number */
    (reprfunc)bool_repr,            /* tp_str */
    &PyInt_Type,                    /* tp_base */
    bool_new,                       /* tp_new */

Upvotes: 21

Pratik Deoghare
Pratik Deoghare

Reputation: 37172

True is 1
False is 0
+ is ADD

Try this:

IDLE 2.6.4      
>>> True == 1
True
>>> False == 0
True
>>> 

Upvotes: 2

Kobi
Kobi

Reputation: 137997

Replace "concatenate" with "add" and True/False with 1/0, as you've said, and it makes perfect sense.

To sum up True and False in a sentence: they're alternative ways to spell the integer values 1 and 0, with the single difference that str() and repr() return the strings 'True' and 'False' instead of '1' and '0'.

See also: http://www.python.org/dev/doc/maint23/whatsnew/section-bool.html

Upvotes: 8

Related Questions