简体   繁体   中英

Use a while loop to find sum of list until negative number or end of list appears

I am supposed to use a while loop to find the sum of a list until it reaches a negative number or until it reaches the end of the list. Here are example lists:

v = [ 10, 12, 3, -5, 5, 6 ]
v = [ 0, 10, 3, 6, 5, 1 ]

The output total sum for both lists should be 25. Here is my code:

result = 0
i = 0
for num in v:
    while num >= 0:
        result += num
        i += 1
print(result)

For both of the lists, my output is just a blank infinite loop. The code I provided was the code I thought made the most sense.

Use if , not while , and break to terminate the loop early. Also, you do not need i .

v = [ 10, 12, 3, -5, 5, 6 ]
# v = [ 0, 10, 3, 6, 5, 1 ]

sum_non_negatives = 0

for num in v:
    if num < 0:
        break
    sum_non_negatives += num
        
print(sum_non_negatives)

You should use OR conditions with a single while loop, like so:

v = [10, 12, 3, -5, 5, 6]
v = [0, 10, 3, 6, 5, 1]

result = 0
i = 0

# while the sum is still at or above 0 and the list isn't out of bounds
while v[i] >= 0 and i < len(v): 
    num = v[i]
    result += num
    i += 1

print(result)

This enables you to avoid break statements, which are generally bad coding practice.

Using only while (not for ):

result = 0
i = 0
while i<len(v) and v[i] >= 0:
    result += v[i]
    i += 1
print(result)

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