Python “如何修复”;TypeError:+;的操作数类型不受支持:';int';和';非类型'&引用;
我正在创建一个程序来计算人类金字塔中每个人顶部的重量,假设每个人都有200磅重。我的问题是函数中的最后一个“elif”,这会导致错误:TypeError:不支持+:“int”和“NoneType”的操作数类型 这需要是我的类的递归函数 我已经尝试了一个“return”语句,并用“tot=”代替了“tot+=”Python “如何修复”;TypeError:+;的操作数类型不受支持:';int';和';非类型'&引用;,python,recursion,computer-science,recursive-query,Python,Recursion,Computer Science,Recursive Query,我正在创建一个程序来计算人类金字塔中每个人顶部的重量,假设每个人都有200磅重。我的问题是函数中的最后一个“elif”,这会导致错误:TypeError:不支持+:“int”和“NoneType”的操作数类型 这需要是我的类的递归函数 我已经尝试了一个“return”语句,并用“tot=”代替了“tot+=” tot = 0.0 def prac(r, c): global tot if c > r: print('Not valid') eli
tot = 0.0
def prac(r, c):
global tot
if c > r:
print('Not valid')
elif r == 0 and c >= 0:
print(tot, 'lbs')
elif r > 0 and c == 0:
tot += (200 / (2 ** r))
prac(r - 1, c)
elif r > 0 and c == r:
tot += (200 / (2 ** r))
prac(r - 1, c - 1)
elif r > 0 and r > c > 0:
tot += (200 + (prac(r - 1, c - 1)) + (prac(r - 1, c)))
prac(r == 0, c == 0)
prac(2, 1)
我希望它能计算出prac(2,1)到300磅,prac(3,1)到425磅,等等。prac函数不返回任何东西,不返回的函数被赋予
None
类型。在上一个elif
语句中,您试图将None
添加到tot,这将引发您得到的错误
我不确定您的代码试图实现什么,因此很难给出正确的答案,但这里有一个猜测:
tot = 0.0
def prac(r, c):
global tot
if c > r:
print('Not valid')
elif r == 0 and c >= 0:
print(tot, 'lbs')
elif r > 0 and c == 0:
tot += (200 / (2 ** r))
prac(r - 1, c)
elif r > 0 and c == r:
tot += (200 / (2 ** r))
prac(r - 1, c - 1)
elif r > 0 and r > c > 0:
x = prac(r - 1, c - 1)
y = prac(r - 1, c)
tot += 200
if x is not None:
tot += x
if y is not None:
tot += y
prac(r == 0, c == 0)
prac(2, 1)
我检查了你的代码,发现你没有返回函数中的任何东西,这使得上一个elif中的事情变得糟糕 在每次迭代中,您都调用该函数进行进一步计算。让我们直接跳到最后一个
elif
。这里,您将添加函数返回的值和静态值。由于函数中没有返回任何内容,因此该值将保存为NoneType
。如果要在另一个或elif处终止循环,请从那里返回值。然后,当您在最后一个elif中调用该函数时,该函数将返回一些内容,并且加法将正常进行
我不知道其中的机制,但我想表达的是,为循环设置一个停止条件,在这个条件下,循环返回值(你还没有考虑到C也小于0的情况)
我希望你明白我的意思。祝你好运!始终发布完整的错误消息并进行完整的回溯。尽量不要在python中使用递归函数。它没有尾部递归优化。