Why doesn't my While loop terminate when the condition is no longer met?

Assignment: Make a function that adds numbers in a list until the sum is greater than 9,000. Once the sum is greater than 9,000 stop adding and print the sum.

Here’s my code:

def over_nine_thousand(lst):
  nums_added = 0
  if len(lst) == 0:
    return nums_added
    while nums_added <= 9000:
      for n in lst:
        nums_added += n
  return nums_added

print(over_nine_thousand([8000, 900, 120, 5000]))

The while loop under the else statement is the part causing me problems. It looks to me like it should terminate as soon as nums_added is greater than 9,000. But every time I run the code I get 14,020 (the sum of all numbers in the list.

How do I get the program to exit the while loop? I think I could test with a bool but that seems less elegant than how I set it up. That said, how I set it up isn’t working, so yea.

the while loop only makes a single iteration, then the for loop adds all the numbers in the list. You could visualize execution here:


that might help. You also have a potential infinity loop when the numbers in the list don’t total over 9000.

Why do you need two loops anyway? I would recommend to use one or the other (while or for), not both.

How would I do it with just one loop? My reasoning was that the While loop is watches the value of the running addition and cuts it off once it reaches the threshhold. Keep adding values only while the sum remains under 9000.

But the for loop will loop over the entire list before the while loop is reached again

why can’t an if condition do this? sounds conditional to me

we only need to loop once until either one of two conditions is met:
we reach the threshold
we run out of items in the list

1 Like