Skip to main content
 首页 » 编程设计

python之理解 Python 按位、算术和 bool 运算符

2025年05月04日31落叶无声

我是 Python 新手,无法理解这一点。有人可以帮我分解声明吗?

n和parity都是整数

n += parity != n & 1 

请您参考如下方法:

表达式被计算为n += (parity != (n & 1)),结果为:

  • n & 1 是一个位掩码,它将整数n 掩码到最低有效位。如果 n 为奇数,则为 1,如果为偶数,则该位为 0。

  • parity != 0 或 parity != 1 产生一个boolean 结果,True 或False,如果 parity 不等于右侧的 0 或 1,则发出信号。

  • 生成的 True 或 False 加到 n 中,就好像您做的那样 n = n + True 或 n = n + False。 Python bool 类型是int 的子类,False 的整数值为0 和True 1 的值。

代码,本质上就是根据parity的值,在n上加上0或1如果 n 当前是偶数或奇数。

一个简短的演示可能会更好地说明这一点。

首先,n & 1 产生 0 或 1:

>>> n = 10  # even 
>>> bin(n)  # the binary representation of 10 
'0b1010' 
>>> n & 1   # should be 0, as the last bit is 0 
0 
>>> n = 11  # odd 
>>> bin(n)  # the binary representation of 11 
'0b1011' 
>>> n & 1   # should be 1, as the last bit is 1 
1 

接下来,parity != 0 或 parity != 1 部分;请注意,我假设 parity 仅限于 0 或 1,它具有其他值确实没有意义:

>>> parity = 0 
>>> parity != 1 
True 
>>> parity != 0 
False 
>>> parity = 1 
>>> parity != 1 
False 
>>> parity != 0 
True 

最后, bool 值是整数:

>>> isinstance(True, int) 
True 
>>> int(True) 
1 
>>> 10 + True 
11 
>>> 10 + False 
10 

这个公式看起来像是在计算一个 CRC checksum .