Alli
Alli

Reputation: 1

Python Error code: IndexError: index error list index out of range

I'm trying to write a function in Python that simulates a horse race. While there's no winner, it clears the screen, shows the list of horses (all have index starting at zero). Then, on the line I've marked, the code messes up. I get the index error list out of range. I'm trying to randomly pick a horse (randomly pick an index number) and add 1 to the value. But I can't seem to figure it out!!

while (no_winner):

    os.system("cls")

    print(horses)

    # randomly assign a horse to step forward
    rando = random.randint(1, HORSE_NUM)
    horses[rando] += 1  #######PROBLEM

    # if the horse exceeds the finish line, he wins
    if (steps > FINISH_LINE):

        winner = horses[index]
        no_winner = False

Upvotes: 0

Views: 194

Answers (1)

Hampton Young
Hampton Young

Reputation: 21

random.randint() is inclusive, so if you get a random integer that is equal to HORSE_NUM it will be out of bounds. try

rando = random.randint(0, HORSE_NUM - 1)

Upvotes: 1

Related Questions