-2

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.

Braiam
  • 1
  • 11
  • 47
  • 78
  • 2
    You should try it if it's for practice. – Nischay Namdev Mar 29 '21 at 15:36
  • This would be a great time to learn how to use a debugger. – Scott Hunter Mar 29 '21 at 15:36
  • 1
    You never change the value of `num` inside the `while` loop, so it's infinite - if `num` is ever greater than or equal to 0, it'll always be greater than or equal to 0. – EJoshuaS - Stand with Ukraine Mar 29 '21 at 15:37
  • I'm not sure what you think `while` does in Python. You say the assignment expects you to use a while loop to solve the problem - what is the intended *purpose* of the loop, do you think? What is there to loop over in your code? (Hint: you are already doing it with a different kind of loop.) – Karl Knechtel Mar 29 '21 at 15:40

3 Answers3

1

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)
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
1

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.

Calvin K
  • 104
  • 2
  • 9
1

Using only while (not for):

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