# Over 9000 Challenge- (While Loop)

Hi all,
I’m practising while-loop on this “Over 9000 Challenge”

Here’s the coding question:

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`.

Here’s my code:

``````def over_nine_thousand(lst):
total = 0
index = 0
while total < 9000:
total += lst[index]
index += 1
if total > 9000:
break
``````

I’m getting an error of:

list index out of range

I’m not sure why the error?

Consider these cases where your code tries to access an out of range index:

• If `lst` is `[]`, then `lst[index]` will try to access `lst` but an empty list doesn’t have any elements, so an index of `0` is out of range.

• If `lst` consists of elements whose sum is not greater than `9000`, then your while condition will always be true. The if condition will never be true, so break will not execute. Yet, you will keep incrementing `index` till you go out of range. For example if `lst` is `[8000, 20, 30]`, then `lst[index]` will eventually try to access `lst` which is out of range.

1 Like