I need help with sarvern shepherd

Is it giving you an infinite loop error? Can you elaborate more on the problem?

As vague as your question is right now, the only advice I can offer is that you should check your while loop’s condition. Make sure you increase the index value by one each time you go through the loop.

Code like this will result in an infinite loop:

index = 0
while index < len(someList):
    someValue = someList[index]
    
    if someValue > 0:
        doSomething()
        index += 1           # index gets incremented
    
    else:                    # when someValue is not greater than 0
        doAnotherThing()     # then index does not get incremented
                             # and someValue = someList(index) will be the same value
                             # so, when the while loops again
                             # and will fail the same if statement again
                             # (and come back to this else block... again and again...)

How to fix it:

index = 0
while index < len(someList):
    someValue = someList[index]
    
    if someValue > 0:
        doSomething()    #note: removed the line: index += 1
    
    else:
        doAnotherThing()
    
    # increment the index only at the last line of a while loop,
    # and outside of any nested code-blocks, like this:
    index += 1

On later levels, you’ll learn how to use for loops, which are much better for going through elements in an array.

2 Likes