Python-在自定义函数中通过for循环添加列表的所有元素

时间:2018-10-30 19:16:05

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

我是新来的,我最近开始学习python,所以我想创建一个函数,该函数可以使用函数中的For循环对列表的所有元素求和,这是我写的:

# Function for sum of all elements of list
def my_num(number):
    count = 0
    for numbers in number:
        count = count + numbers
        # return count
my_list = list(range(1, 2, 3, 4))
print(my_num(my_list))

正在打印-None

我想使用功能my_num

将my_list的所有数字相加

预先感谢!

1 个答案:

答案 0 :(得分:1)

在您的代码中,函数结尾没有return语句。没有return语句的任何函数都将返回None

def my_num(number):
    count = 0
    for num in number:
        count += num
    return count
my_list = list(range(1, 5)) # range(start, end)
print(my_num(my_list)) # -> 10

或者,Python已经具有内置函数:sum(),该函数返回任何数字列表的总和。

my_list = list(range(1, 5))
print(sum(my_list)) # -> 10

此外,range()仅接受3个参数:start, end, step。获取[1, 2, 3, 4]的正确方法是使用range(1, 5),其中1是包含性的,而5是排除性的。