繁体   English   中英

如何解决“ TypeError:+不支持的操作数类型:'int'和'NoneType'”

[英]How to fix “TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'”

我正在创建一个程序,假设每个人都方便地重达200磅,它可以计算出金字塔中每个人的体重。 我的问题是函数中的最后一个'elif',它引发错误:TypeError:+不支持的操作数类型:'int'和'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磅,prac(3,1)到425等。

prac函数不返回任何内容,不返回的函数指定为None类型。 在最后一个elif语句中,您尝试将tot添加为None ,这将引发错误。

我不确定您的代码要完成什么,因此很难发布正确的答案,但这是一个猜测:

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的情况。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM