How to fix "TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'"

How to fix "TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'"

我正在创建一个程序来计算人体金字塔中每个人的体重,假设每个人的体重均为 200 磅。我的问题是函数中的最后一个 'elif',它会引发错误:TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'.

这需要是我的 class 的递归函数。

我已经尝试了 'return' 语句并且 'tot =' 而不是 '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:
        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 函数没有 return 任何东西,没有 return 的函数被赋予 None 类型。在最后一个 elif 语句中,您试图将 None 添加到 tot,这将引发您得到的错误。

我不确定你的代码试图完成什么,所以很难post一个正确的答案,但这是一个猜测:

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)

我检查了你的代码,发现你没有在你的函数中 returning 任何东西,这会使最后一个 elif 中的事情变得糟糕。

在每次迭代中,您都在调用函数以进行进一步计算。让我们直接跳到最后一个 elif。在这里,您通过函数添加值 returned 以及静态值。由于您未在函数中 returning 任何内容,因此该值将保存为 NoneType。如果您打算在 else 或 elif 处终止循环,return 那里的值。然后,当您在最后一个 elif 中调用该函数时,该函数将 return 一些东西并且加法将正确进行。

我不知道其中的机制,但我想表达的是为循环创建一个停止条件,其中 return 值 (你还没有解决 C 小于 0 的情况。

希望你明白我的意思。祝你好运!