简体   繁体   中英

Sum of all numbers in a sequence for loop

I'm new to python and I'm doing exercises regarding loops. I'm wondering how can I get sum of all the numbers in a for loop sequence?

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

I've sorted it this way, but it's a different exercise.

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 ))

I would like to see a solution for the first case without defining a function with it's parameter of sequence, just as it is in the first code block. Thank you in advance. print(sum(num)) doesn't work since object is not iterable.

If we know for sure that 0 exists this can be done in a fairly cheeky way (at the cost of having to iterate the list twice and the creation of a new list):

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

But the proper way to do it is with an explicit loop like you tried, just with the correct logic:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM