What is the role of “&” when used with integers in python? [duplicate] - python

This question already has answers here:
What does & mean in python [duplicate]
(5 answers)
Closed 3 years ago.
I mistakenly wrote the line of code, I expected it to give me an error but it returned an answer.
Codx = [num for num in range(1,9) if num & 2 = 0]
Print (codx)
I got the answer
[1,4,5,8]
Then I did
Print(3&2)
Answer was 2
Print(5&2)
Answer was 0
What’s the role of the ampersand?

That's the bitwise-and operator: For the official documentation, it does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.

Related

Negative one to the power of two question - i.e. (-1)**2 [duplicate]

This question already has answers here:
Calculation error with pow operator
(4 answers)
Closed 1 year ago.
Can someone explain the difference between these two expressions in Python:
(-1)**2 == 1
-1**2 == -1
Why do the parentheses change the outcome?
The parentheses means the whole value inside is will be raised to the power 2.
(-1)**2 == 1
So -1*-1 is 1
No parentheses means the - will be taken out of the equation and added to the end of the answer.
1) -1**2
2) 1**2
3) 1
4) -1
Python handles this the same way the world does :)

Curious about the function of ~in the following code [duplicate]

This question already has answers here:
The tilde operator in Python
(9 answers)
Closed 1 year ago.
pd_selftest = pd_selftest[pd_selftest['SICCD'] != 0]
pd_selftest = pd_selftest[~pd_selftest['SICCD'].isnull()]
I'd like to know what the function of the ~ is in the above code.
That's the bit-wise invert or not operator. So, it returns only those lines where the SICCID column is not null. I would probably use the word not in this case.

How to convert to log base 2? [duplicate]

This question already has an answer here:
NumPy: Logarithm with base n
(1 answer)
Closed 2 years ago.
How can i convert the following code to log base 2?
df["col1"] = df["Target"].map(lambda i: np.log(i) if i > 0 else 0)
I think you just want to use np.log2 instead of np.log.

Python 3 - convert mathematical action to integer [duplicate]

This question already has answers here:
Math operations from string [duplicate]
(8 answers)
Closed 6 years ago.
I have a string with a formula 5 - 3, and I need to get the result in integer. How could I do that?
use eval function:
eval("5 - 3") # 2
test = "5-3"
print(eval(test))
Gives 2

Python 3 integer division [duplicate]

This question already has answers here:
Why does integer division yield a float instead of another integer?
(4 answers)
Closed 6 years ago.
In Python 3 vs Python 2.6, I've noticed that I can divide two integers and get a float. How do you get the Python 2.6 behaviour back?
Is there a different method to get int/int = int?
Try this:
a = 1
b = 2
int_div = a // b

Categories

Resources