0
print(False + True)

Why does this return an integer 1

Is there any explanation?

Also print((int(False + True) == (False + True)) )

returns True, so this means that True + False is indeed an integer ?

VLC
  • 127
  • 7
  • 1
    This question has an answer here: https://stackoverflow.com/questions/8169001/why-is-bool-a-subclass-of-int – natka_m Nov 22 '20 at 21:15
  • 1
    In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The Python documentation – Dani Mesejo Nov 22 '20 at 21:17
  • 1
    also related https://stackoverflow.com/q/2764017/4744341 – natka_m Nov 22 '20 at 21:17

4 Answers4

5

From the python 3 docs The standard type hierarchy:

Booleans (bool)

These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

So yes, they are a subtype of integer and behave mostly like them.

(Python 2 operates differently, but it is end-of-life so I am not adding its rules)

tdelaney
  • 73,364
  • 6
  • 83
  • 116
3

bool is a subclass of int:

>>> bool.mro()
[<class 'bool'>, <class 'int'>, <class 'object'>]
>>> issubclass(bool, int)
True
ForceBru
  • 43,482
  • 10
  • 63
  • 98
2

print(False + True) returns 1 because int(True) = 1 and int(False) = 0

True has a value of 1 and False has a value of 0. They are binary values. You can use them interchangeably with their integer equivalents.

user14678216
  • 2,886
  • 2
  • 16
  • 37
0

Not Integers per say, they are binary digits {True:1, False:0}

Savvii
  • 480
  • 4
  • 9
  • 3
    What are "binary digits"? Python doesn't seem to have a concept of binary digits. Also, `True.__sizeof__() == 28`, so `True` definitely doesn't occupy one bit, like a "binary digit" would. – ForceBru Nov 22 '20 at 21:18