Sud*_*rew 1 python if-statement
我创建了一个与x和y变量进行比较的函数.函数内部有很多嵌套的elif来比较x和y然后返回整数.问题是现在,当它在特定的elif语句中运行时,虽然语句是正确的,但它没有执行语句.
def convertTo(self, x, y):
if( x == 0 & y == 0):
return 0
if( x == 0 & y == 1):
return 1
if( x == 0 & y == 2):
return 2
if( x == 0 & y == 3):
return 3
if( x == 1 & y == 0):
return 4 # Didn't return this line even though x = 1 and y = 0
else
return None
def main():
self.convertTo(0,0)
self.convertTo(0,1)
self.convertTo(0,2)
self.convertTo(0,3)
self.convertTo(1,0) # return None? Why?
Run Code Online (Sandbox Code Playgroud)
您正在执行链式相等比较,而这种比较并没有按照您的想法进行.&首先执行按位,因为它具有比其更高的优先级==.
更换:
x == 1 & y == 0
# 1 == 1 & 0 == 0
# 1 == 0 == 0 False!
Run Code Online (Sandbox Code Playgroud)
附:
x == 1 and y == 0
Run Code Online (Sandbox Code Playgroud)
请参阅:运算符优先级
| 归档时间: |
|
| 查看次数: |
426 次 |
| 最近记录: |