相加多个数字并将输出作为等式返回

问题描述 投票:0回答:2

我正在定义一个函数,该函数将多个数字作为输入并返回所有数字的总和。多少数字将成为输入的一部分是未知的。同样,此函数的输出必须包含为得到该结果而遵循的数学方程式。

例如,如果在调用函数时给出以下数字:2,3,2,1;该函数将计算总和,即8,并输出以下内容:2 + 3 + 2 + 1 = 8(作为字符串)。

到目前为止,我已经能够完成第一部分(即计算),但是我不知道如何创建将输出数学方程式的return语句。这是我所拥有的:

def my_math(*args):
    sum = 0
    for n in args:
        sum += n
    return "= {}".format(sum) #this is where I'm stuck. I don't know how to code the numbers and the '+' signs that would appear before the '=' sign
python
2个回答
1
投票

使用连接方法:

return " + ".join(str(x) for x in args) + f" = {sum}"

我在这里使用f字符串来简化格式。


0
投票

您可以将string.formatstring.join一起使用

return "{} = {}".format(' + '.join(map(str,args)),sum(args))
© www.soinside.com 2019 - 2024. All rights reserved.