【问题标题】:How to fix "TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'"如何修复“TypeError:+ 的不支持的操作数类型:'int' 和 'NoneType'”
【发布时间】:2020-01-17 23:07:27
【问题描述】:

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

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

我已经尝试过“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 lbs , prac(3,1) 到 425 等。

【问题讨论】:

  • 总是发布带有完整回溯的整个错误消息
  • 尽量不要在python中使用递归函数。它没有尾递归优化。

标签: python recursion computer-science recursive-query


【解决方案1】:

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)

【讨论】:

    【解决方案2】:

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

    在每次迭代中,您都调用函数进行进一步计算。让我们直接跳到最后一个elif。在这里,您将函数返回的值与静态值一起添加。由于您没有在函数中返回任何内容,因此该值将保存为 NoneType。如果您打算在 else 或 elif 处终止循环,请从那里返回值。然后当你在最后一个 elif 中调用该函数时,该函数将返回一些内容,并且添加将正常进行。

    我不知道其中的机制,但我想传达的是为返回值的循环创建一个 停止条件(您还没有满足 C 变为也小于 0。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-27
      • 2014-03-31
      • 2021-05-23
      • 2015-10-15
      • 2016-08-25
      • 1970-01-01
      • 2013-02-08
      • 2016-10-22
      相关资源
      最近更新 更多