Python-为什么我的 elif 语句没有在考虑负数的递归乘法中得到评估 [英] Python-Why aren't my elif statements not getting evaluated in this recursive multiplication which takes into account negative numbers
问题描述
我在 python 中查找了一些 2 个数字的递归乘法,但没有一个考虑到负数的可能性,或者如果他们考虑了,他们就没有解释整个步骤.
Hi I have looked up a few recursive multiplication of 2 numbers in python, but none of them take into account the possibility of negative numbers or if they do they don't explain the entire steps.
我已经编写了以下程序,但出现错误,有人可以告诉我它有什么问题吗?
I have coded the following the program but I am getting an error, can someone please let me know what is wrong with it?
def mult(a,b):
if a==0 | b==0:
return 0
elif a==1:
return b
elif a > 0 & b >0:
return b + mult(a-1,b)
elif a < 0 & b > 0:
return - b + mult(a+1,b))
elif a > 0 & b < 0:
return - b + mult(a-1, b))
else:
return -b + mult(a+1, b)
print(mult(-4,5))
推荐答案
|
和 &
是按位运算符,不是逻辑运算符,它们的 (相对)高优先级 意味着 a >0 &b >0
被解析为 a >(0 & b) >0
,这不是你想要的.使用 or
和 and
代替.
|
and &
are bitwise operators, not logical operators, and their (relatively) high precedence means that a > 0 & b >0
is parsed as a > (0 & b) > 0
, which is not what you want. Use or
and and
instead.
这篇关于Python-为什么我的 elif 语句没有在考虑负数的递归乘法中得到评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!