首页 > 解决方案 > for循环序列中所有数字的总和

问题描述

我是 python 新手,我正在做有关循环的练习。我想知道如何获得 for 循环序列中所有数字的总和?

for num in (12, 1, 3, 33, -2, -5, 7, 0, 22, 4): # this is the sequence and it shouldn't be altered
    if num == 0: # once it encounters 0 it should stop
        print("Done")
        break
        continue
    else:
            print(sum(num)) # otherwise print the sum of all numbers

我以这种方式对其进行了排序,但这是一个不同的练习。

def process(numbers):
    for num in numbers:
        if num == 0:
            break
    else:
        x = sum(numbers)
        print(x)
    return 'Done'

process(( 12, 4, 3, 33, -2, -5, 7, 0, 22, 4 ))

我希望看到第一种情况的解决方案,而不用定义带有序列参数的函数,就像在第一个代码块中一样。先感谢您。print(sum(num)) 不起作用,因为对象不可迭代。

标签: python

解决方案


如果我们确定 0 存在,这可以以一种相当厚颜无耻的方式完成(代价是必须迭代列表两次并创建一个新列表):

sum(numbers[:numbers.index(0)]) 

但是正确的方法是使用您尝试过的显式循环,只需使用正确的逻辑:

def process(numbers):
    s = 0
    for num in numbers:
        if num == 0:
            break
        s += num
    print(s)
    return 'Done'

推荐阅读