-1

我是新来的,我最近开始学习 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_listmy_num

提前致谢!

4

1 回答 1

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), where 1is inclusive and 5is Exclusive。

于 2018-10-30T19:59:56.623 回答