【问题标题】:How do I subract results from different functions from each other in Python?如何在 Python 中将不同函数的结果相减?
【发布时间】:2019-08-29 01:45:54
【问题描述】:

我有一个函数,我已经写出来了,想对它进行数学运算,就像我对数字一样。

例如,对于下面的代码,我想采用 Sup(3) - Sup(2) = result,但这不起作用。我可以使用我定义的函数并对它们执行数学运算,就像我们对数字执行数学运算一样(例如,2 * 2 = 4)吗?

对于 n = 2,我的结果是 1.083 对于 n = 3,我的结果是 1.717,使用下面的代码。

def Sup(n):
    mylist = []
    for n in range (2,2**n+1):
        Su = (1/n)
        mylist.append(Su)
    #print(mylist)
    print (sum(mylist))

当我尝试此操作时,我收到以下错误:

---> 12 Sup(2)- Sup(3)

TypeError: unsupported operand type(s) for -: 'NoneType' and 'NoneType'neType'

What does this mean?

【问题讨论】:

  • Sup 不返回任何内容。试试return sum(mylist) 而不是print

标签: python list math operators subtraction


【解决方案1】:

我可以使用我定义的函数并对它们执行数学运算,就像我们对数字执行数学运算一样吗? 是的,你可以,假设你的函数返回数字。

这是什么意思? 正如 cmets 中所指出的,这意味着您的函数不返回任何内容。将return 添加到您的函数中应该可以解决问题:

def Sup(n):
    mylist = []
    for n in range (2,2**n+1):
        Su = (1/n)
        mylist.append(Su)
    #print(mylist)
    print (sum(mylist))
    return sum(mylist)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    相关资源
    最近更新 更多