Python:带有for循环的数字列表的总和 [英] Python: Total sum of a list of numbers with the for loop

查看:117
本文介绍了Python:带有for循环的数字列表的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,但我遇到了这个问题:

I'm new to Python and I have this problem:

我需要编写一个Python函数,该函数使用for循环将数字列表的和返回给我.

I need to program a Python function that gives me back the sum of a list of numbers using a for loop.

我只知道以下内容:

sum = 0
for x in [1,2,3,4,5]:
      sum = sum + x

print(sum)

推荐答案

我认为您的意思是如何将其封装起来以用于一般用途,例如在一个函数中:

I think what you mean is how to encapsulate that for general use, e.g. in a function:

def sum_list(l):
    sum = 0
    for x in l:
        sum += x
    return sum

现在您可以将其应用于任何列表.例子:

Now you can apply this to any list. Examples:

l = [1, 2, 3, 4, 5]
sum_list(l)

l = list(map(int, input("Enter numbers separated by spaces: ").split()))
sum_list(l)

但是请注意,已经内置了 sum

But note that sum is already built in!

这篇关于Python:带有for循环的数字列表的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆