带 If 语句和比较运算符的位运算符。这个 if 语句是如何工作的?
Bitwise Operator with If Statement and comparison Operators. How does this if statement work?
a = 2
b = 1
if a == 2 | b == 1:
print(a, b)
this won't print the values of a & b
a = 2
b = 1
if ((a == 2) | (b == 1)):
print(a, b)
this will print the values
为什么会这样?
Python 中的运算符 ==
的优先级低于运算符 |
。所以:
a == 2 | b == 1
相当于:
a == (2 | b) == 1
反过来,这相当于:
(a == (2 | b)) and ((2 | b) == 1)
鉴于 a==2
,无论 b
.
至少有一个子表达式必须为假
|
是按位 OR
运算符,它的优先级高于 ==
。因此,如果不使用括号,2 | b
会在第一个程序的开头执行。
(2 | b) -> (2 | 1) -> (3)
然后勾选a==3
时,returns为假,因为a=2
如果您想通过检查 a 和 b 的值来执行语句,我认为您可以在这里使用 or
而不是 |
。
a = 2
b = 1
if a == 2 | b == 1:
print(a, b)
this won't print the values of a & b
a = 2
b = 1
if ((a == 2) | (b == 1)):
print(a, b)
this will print the values
为什么会这样?
Python 中的运算符 ==
的优先级低于运算符 |
。所以:
a == 2 | b == 1
相当于:
a == (2 | b) == 1
反过来,这相当于:
(a == (2 | b)) and ((2 | b) == 1)
鉴于 a==2
,无论 b
.
|
是按位 OR
运算符,它的优先级高于 ==
。因此,如果不使用括号,2 | b
会在第一个程序的开头执行。
(2 | b) -> (2 | 1) -> (3)
然后勾选a==3
时,returns为假,因为a=2
如果您想通过检查 a 和 b 的值来执行语句,我认为您可以在这里使用 or
而不是 |
。