【问题标题】:Summing values with a for loop使用 for 循环对值求和
【发布时间】:2014-03-13 19:06:57
【问题描述】:

说明:

定义一个名为summer() 的函数,用于对数字列表中的元素求和。 summer() 采用单个列表参数。首先需要将一个累加器初始化为零,然后使用 for 循环将列表中每个元素的值相加,最后将总和返回给调用程序。

问题:

我知道如何使用 sum() 函数很容易地做到这一点,但我不允许使用它。我必须找到一种方法来汇总列表值并打印该总和。

>>> x = [9, 3, 21, 15]
>>> summer(x)
48

我尝试过的:

xlist=[9,3,21,15]
sumed=0
def summer(x):
    for i in x:    
    sumed+=i

print(sumed)


summer(xlist)

我不断得到'sumed' ref。在分配这个之前

【问题讨论】:

  • 你有没有尝试过?您是否阅读了课堂材料中解释 for 循环如何工作的部分?
  • @balki 我将原件编辑为我尝试使用的内容

标签: python for-loop python-3.x sum


【解决方案1】:

让我一步一步翻译说明:

  • 第一步

定义一个名为summer()的函数,它对列表中的元素求和 数字。

def summer():
  "This function sums the elements in a list"
  • 第二步

summer() 接受一个列表参数。

def summer(a_list):
  "This function sums the elements in a list"
  • 第三步

首先你需要将一个累加器初始化为零

def summer(a_list):
  "This function sums the elements in a list"
  accumulator = 0
  • 第四步

,然后使用for循环将列表中每个元素的值相加,

def summer(a_list):
  "This function sums the elements in a list"
  accumulator = 0
  for elem in a_list:
    accumulator+= elem

最后将总和返回给调用程序。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 2021-04-18
    • 2022-01-02
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 2019-01-05
    相关资源
    最近更新 更多