![](/img/trans.png)
[英]Write a function which squares a number and then use it to write a function which takes three integers and returns the sum of their squares
[英]function (sum_it_up) that takes any number of parameters and returns to sum
如何编写一个接受任意数量参数并返回 sum 的函数 (sum_it_up)?
例如,这应该打印 22:
total=sum_it_up(1,4,7,10)
print(total)
解决方案:
def sum_it_up (a,b,c,d):
print("The total is {0}".format(a+b+c+d))
sum_it_up(1,4,7,10)
sum_it_up(1,2,0,0)
上面的解决方案缺少 return 语句。 有任何想法吗? 谢谢!
正如@georg 建议的那样,您应该使用*args
来指定一个函数可以采用可变数量的未命名参数。
args
将函数作为元组提供。 作为一个可迭代对象,这可以被 Python 的内置sum
直接接受。 例如:
def sum_it_up(*args):
print('The total is {0}'.format(sum(args)))
sum_it_up(1,4,7,10) # The total is 22
sum_it_up(1,2,0,0) # The total is 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.