![](/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.