[Solved] Python - Over 9000 Challenge

Hello everyone!

I am working on this exercise and I have something I don’t quite understand.

Here is the code:

#Write your function here
def over_nine_thousand(lst):
  total = 0
  for n in lst:
    total += n
    if total > 9000:
      return total
      break
  return total

#Uncomment the line below when your function is done
print(over_nine_thousand([8000, 900, 120, 5000]))

This is a correct answer, but I was wondering if I could do it with a while loop. Something like this:

#Write your function here
def over_nine_thousand(lst):
  total = 0
  while total <= 9000:
    for n in lst:
      total += n
  return total

#Uncomment the line below when your function is done
print(over_nine_thousand([8000, 900, 120, 5000]))

I get a result of 14020. Here are the specific instructions:

"Create a function named over_nine_thousand() that takes a list of numbers named lst as a parameter.

The function should sum the elements of the list until the sum is greater than 9000 . When this happens, the function should return the sum. If the sum of all of the elements is never greater than 9000 , the function should return total sum of all the elements. If the list is empty, the function should return 0 .

For example, if lst was [8000, 900, 120, 5000] , then the function should return 9020 ."

The problem is that it did not return 9020. Something did not work with the while loop. Can someone explain???

You can always throw in some print statements or similar to start debugging. Consider how your for loop typically operates and what the original answer does to deal with the for loop.

Note that the while loop condition is only checked at the start of each iteration.

1 Like

Oh ok I understand, the for is inside the while. This causes the for to run through and add all the numbers and add them all before the while goes again. So in this case, the if loop would be best. Thanks!!!

1 Like