Reputation: 95
I am studying the Python built-in method int(x)
, which casts a variable to int
. The documentation is at https://docs.python.org/2/library/functions.html#int.
In a code I found:
errors += int(update != 0.0)
This code simply increases or decreases an error variable. What i see is a conditional as a variable, even though the method doesn't take Boolean values. How is this possible?
Upvotes: 1
Views: 132
Reputation: 225074
The Python 3 documentation is ever so slightly more straightforward than the 2 documentation here, so I’ll quote it:
Return an integer object constructed from a number or string
x
, or return0
if no arguments are given. Ifx
is a number, returnx.__int__()
.
So int
accepts a string or a number. Booleans aren’t strings, but they are in fact numbers! Following the link to Numeric Types – int
, float
, complex
explains that…
There are three distinct numeric types: integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of integers.
which you can confirm in the REPL:
>>> import numbers
>>> isinstance(False, int)
True
>>> isinstance(True, numbers.Numeric)
True
and by doing math with booleans, which act as the integer values 0 and 1 as one would expect:
>>> True * 5
5
>>> math.acos(False)
1.5707963267948966
Upvotes: 2
Reputation: 562
Booleans are a sub class of Integers in python and internally and False
is represented as 0
in Python.
Upvotes: 0
Reputation: 4580
Consider two possibilities:
int(True)
and int(False)
First case will evaluate to 1
and second to 0
hence, errors
will either increase by 1
or by 0
refer to the doc
Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to convert any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).
Upvotes: 2