让我一步一步地翻译说明:步骤1Define a function called summer() that sums the elements in a list of
numbers.def summer():
"This function sums the elements in a list"步骤2summer() takes a single list argument.
^{pr2}$
步骤3First you need to initialize an accumulator to zerodef summer(a_list):
"This function sums the elements in a list"
accumulator = 0步骤4, then use a for-loop to add the value of each element in the list,def summer(a_list):
"This function sums the elements in a list"
accumulator = 0
for elem in a_list:
accumulator+= elemand finally return the total sum to the calling program.def summer(a_list):
"This function sums the elements in a list"
accumulator = 0
for elem in a_list:
accumulator+= elem
return accumulator
现在,您可以在shell中尝试:>>> def summer(a_list):
... "This function sums the elements in a list"
... accumulator = 0
... for elem in a_list:
... accumulator+= elem
... return accumulator
...
>>> x = [9, 3, 21, 15]
>>> summer(x)
48