variable - what does it mean to return true in python
Why does ~True result in-2? (2)
~True == -2 is not surprising if
~ means bitwise inversion...
Truecan be treated as an integer and
- integers are represented in Two's complement
- fixed the mixing between integer representation and bitwise inversion operator
- applied another polishing (the shorter the message, the more work needed)
In Python console:
Why? Can someone explain this particular case to me in binary?
bool type is a subclass of
int (for historical reasons; booleans were only added in Python 2.3).
See PEP 285 for why
bool is a subclass of
If you wanted the boolean inverse, use
>>> not True False >>> not False True
If you wanted to know why
-2, it's because you are inverting all bits in a signed integer;
1111110 which in a signed integer is a negative number, see Two's complement:
>>> # Python 3 ... >>> import struct >>> format(struct.pack('b', 1), '08b') '00000001' >>> format(struct.pack('b', ~1), '08b') '11111110'
where the initial
1 bit means the value is negative, and the rest of the bits encode the inverse of the positive number minus one.