Distinguish Two "And" in Python

2022-03-01 13:08:50 浏览数 (1)

Most important first: & is a bit-wise operator while “and” is a logical connector.

Property of these two

First I need to cite a piece from the instructor given link:

(year%4==0 & 92) will be evaluated. year%4==0 = 0 (0 & 92) ==> 0000000 & 1011100 ==> 1011100 ==>92, which is a True value because it is non zero value. Hence the result will be True.

There are some mistake made by the author (reason has discussed in followup discussions) and a correct version would be like:

year = 1992 Evaluate (year%4==0 & 92). Since the & has higher precedence we have (year%4 == (0 & 92)) (0 & 92) ==> 0000000 & 1011100 ==> 0000000 ==>0, which is a False value because it is zero. Then (year%4 == 0) gives us true.

We can see that & is a bitwise operator, strictly follow the bit string, carry “and” operation on each pair of them. Then give a result bit string.

Then what about “and”? “and” is a lazy guy (just like and in Haskell) when it encountered a false result, it will stop and give an give back that value. What does this mean? Wait, let me explain. A more mathematical notation of “and” is a logic connector we know that if there is a thing is false, the whole statement connected with “and” is false. So, “and” simply give the first false statement it encountered and say “here you are, this is the answer”. So does all statement is true, it will give the last true statement.

still use examples from the link above:

代码语言:javascript复制
a, b = 9, 10
print(a & b)
print(a and b)

They will give 8 and 10 respectively. 8 is because of bit-wise calculation. “and” processed to the last value and simply gives 10 as result, since a and b are both none zero values which means true.

Then let’s talk about list operation.

& is sadly not support some kind of bit-wise calculation of a list. As the instructor said we can use some func in library Pandas instead of trying &.

Then “and”. I guess a list defaults to be the true value, so no matter how many lists connect with “and” and no matter what the value those lists include, the output would be the last list. Like the example below, it always gives us List4 (ridiculously correct answer).

代码语言:javascript复制
list1 and list2 and list3 and list4

There may be someplace we can use this property, but if we only care about the answer, I guess we have to try func in library Pandas.

ps: the second part has not been tested and what are those func or how to use Pandas are still unrevealed. If you find any mistake or want to add more points, feel free to edit, it will be great.

0 人点赞