This question already has answers here:
The tilde operator in Python
(9 answers)
Closed 1 year ago.
I'd like to check if a dataframe is empty or not. use ~df.empty return -2 while using Not df.empty return False.
why I cannot use ~?
df.empty
True
~df.empty
-2
not df.empty
False
In Python ~ is the bitwise not operator, it takes the bits and swaps 1s and 0s. For boolean values, true is 0b00000001 and false is 0b00000000 so ~true is 0b11111110 which, since bool a special case one byte int, evaluates as the signed integer value -2.
not on the other hand is the logical not operator, if a value is true/truthy it returns false, if a value is false/falsy it returns true, it doesn't care about the specific bits, only that (generally) at least one of the bits is 1.
Operation
True0b00000001
False0b00000000
~
-20b11111110
-10b11111111
not
False0b00000000
True0b00000001
Related
This question already has answers here:
What does & mean in python [duplicate]
(5 answers)
Bitwise operation and usage
(17 answers)
Python if statement without == operator
(3 answers)
'if' not followed by conditional statement
(7 answers)
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Closed 3 months ago.
I have the following code segment in python
if mask & selectors.EVENT_READ:
recv_data = sock.recv(1024)
if recv_data:
data.outb += recv_data
else:
print(f"Closing connection to {data.addr}")
Would I read this as: 'if mask and selectos.EVENT_READ are equivalent:'
And similarly: 'if recv_data is equivalent to true:'
Help is greatly appreciated!
For the second assumptions, yes.
if var_name: is shorthand of saying if var_name evaluates to a truthy value.
Your first assumption is wrong though, a logical AND operation in python is actually and, not & - many languages do use an ampersand as a logical and, but this is usually a double ampersand, as in &&. A single ampersand is usually a bitwise AND, not a logical AND.
So in your code above, the first if statement is doing a bitwise (binary) AND on the selectors.READ_EVENT with a bitmask of mask. Basically its a way of asking if the values match, in a binary way. So if READ_EVENT is 010 and the mask is also 010, then the logic evaluates to true. Otherwise
All values have an inherent Boolean value. For the bytes value returned by sock.recv, the empty value b'' is false and all other values are true. This is a short, idiomatic way of writing
if recv_data != b'':
...
The & is a bitwise AND operator. The result of mask & selectors.EVENT_READ produces a value where a bit is 1 if both mask and selectors.EVENT_READ have a 1, and 0 otherwise. The result of that is an integer which may or may not be 0 (and for int values, 0 is false and all others are true).
Basically, mask & selectors.EVENT_READ is true if and only if any of the bits set in selectors.EVENT_READ are also set in mask.
This question already has answers here:
How does the bitwise complement operator (~ tilde) work?
(18 answers)
Closed 2 years ago.
I found that ~True is -2 and ~False is -1. Why is this?
W3Schools says that ~ inverts all the bits. Why isn't ~True is False and ~False is True?
Reasoning attempts
My attempt to explain these:
True is +1, and the bits of +1 are inverted. + is inverted to -.
1 in two-digit binary is 01, so inverted bits: 10, ie 2. So result is -2.
False is +0, + is inverted to -, 0 in two-digit binary is 00, all the bits inverted, 11, which is 3 - it should be 1.
Sources
This answer paints a more complicated picture:
A list full of Trues only contains 4- or 8-byte references to the one
canonical True object.
The PyTables User’s Guide says:
bool: Boolean (true/false) types. Supported precisions: 8 (default)
bits.
These don't support the simplistic (and apparently wrong) reasoning above.
First of all, I'd use the not operator to invert Boolean values (not True == False, and vice versa). Now if Booleans are stored as 8-bit integers, the following happens:
True is 0000 0001. Hence ~True yields 1111 1110, which is -2 in two's-complement representation.
False is 0000 0000. Hence ~False yields 1111 1111, which is -1.
This question already has answers here:
Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?
(3 answers)
Closed 2 years ago.
Why "~False" is -1 in Python?
I was using a boolean variable in Python. When I try to do not of that, it returns -1. I want to understand why so? why a variable a changing its data-type duo to this operation.
Trying to add more details
b0 = False
print(type(b0))
b0 = ~b0
print(type(b0))
>>bool
>>int
The tilde ~ is the bitwise 'not' operator, not the boolean 'not' operator. To do a not you probably want 'not False'.
The reason for it changing its data type is that it treats False as binary 0 and then flips it to -1.
This question already has answers here:
Does Python evaluate if's conditions lazily? [duplicate]
(7 answers)
Closed 4 years ago.
print(True or 5 / 0 > 3)
This is my code but it returns True
Is there a reason why it doesn't return a Zero Division Error?
Its because True is always true. The Python interpreter does not evaluate the right side of the or operator in this case, because the outcome of an or expression is always true if one of its operands is true. If you enter5 / 0 > 3 or True than you get your devision by zero error
This question already has answers here:
Python Bool and int comparison and indexing on list with boolean values
(4 answers)
Closed 4 years ago.
In [1]: a=5
In [2]: print(["is odd", "is even"][a % 2 == 0])
is odd
In [3]: [a%2 == 0]
Out[3]: [False]
What I understood is a % 2 == 0 evaluates to True or False.
So if it is True then that is equivalent to 1 and using list indices it's going to print 'is even'.
I've read this and came to know bool is an instance of int.
So when used as in index bool evaluates to it's equivalent number i.e 0 or 1.
My question
Based on intuition we can know whether it's going to be an int or bool
But how does Python know? Does it have any criteria when to use as bool and when to use as int? Anything from Python3 documentation would be appreiated.
In Python 2.x this is not guaranteed as it is possible for True and False to be reassigned. However, even if this happens, boolean True and boolean False are still properly returned for comparisons.
In Python 3.x True and False are keywords and will always be equal to 1 and 0.
Under normal circumstances in Python 2, and always in Python 3:
False object is of type bool which is a subclass of int:
object
|
int
|
bool
It is the only reason why in your example, ['zero', 'one'][False] does work. It would not work with an object which is not a subclass of integer, because list indexing only works with integers, or objects that define the __index__ method (thanks mark-dickinson).
Edit:
It is true of the current Python version, and of that of Python 3. The docs for Python 2.6 and the docs for Python 3 both say:
There are two types of integers: [...] Integers (int) [...] Booleans (bool)
and in the boolean subsection:
Booleans: These represent the truth values False and True [...] 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 booleans are explicitly considered as integers in Python 2.6 and 3.
The bool instances, True and False, are separate from the int instances, 0 and 1. The thing is that the bools behave like integers in many contexts. Such as True+True which is 2. However if we check if they are the same object we see it is not: True is 1. On the other hand it is true that True is True. Here's an example which behaves like integers but are printed as True and False and compares differently with is.
class Bool(int):
def __repr__(self):
return 'True' if self==1 else 'False'
https://docs.python.org/3/library/stdtypes.html#bltin-boolean-values