True + 1 + True = 3
Permalink
Try this in Python's REPL:
True + 1 + True
# outputs: 3
What?! Yeah, it's surprising.
Bool values - True
and False
- can be used as numbers in Python. True
is 1
and False
is 0
.
So we can do funny things like:
5 * False
# outputs: 0
sum([True, True, True, True, True])
# outputs: 5
True + 1 + False *10
# outputs: 2
Ok. I'm sure you get the point.
Why is that?Permalink
What if we ask for a type of True or False?
type(True)
# outputs: <class 'bool'>
type(False)
# outputs: <class 'bool'>
We can see that values True and False are of the type of the class bool
. So why does it work like numbers too?
It is because class bool
inherits from class int
. The following code is in Python's source code:
class bool(int):
"""
bool(x) -> bool
Returns True when the argument x is true, False otherwise.
The builtins True and False are the only two instances of the class bool.
The class bool is a subclass of the class int, and cannot be subclassed.
"""
...
So bool values are backed by numbers in Python. It doesn't cause any problems most of the time, but sometimes we need to be careful.
x = True
isinstance(x, int)
# outputs: True
In the above code, we assign True to variable x. Then we check if x
is an instance of class int
. And it returns True
. We already know that it is
because bool
inherits from int
.
So any code that expects int
will also work if it receives bool
values
instead.
By work, I mean it will not crash. But will it do what the user of that code is expecting? Possibly not, because bool values have a different purpose than int (number) values.
True
and False
are keywords in Python 3. True
is always 1
, and False
is always 0
.
int(True)
# outputs 1
int(False)
# outputs 0
We can also turn any int to bool:
bool(1)
# outputs True
bool(7)
# outputs True
bool(-8)
# outputs True
bool(0)
# outputs False
bool(number)
will output True
for any number except 0. Keep this in mind. Every int
number is True
except for 0
, which is False
.
You might also like
Join the newsletter
Subscribe to learn how to become a Remote $100k+ developer. Programming, career & Python tips.