Jonty Morris
Jonty Morris

Reputation: 807

Python list index is out of range error

I've been tasked with making a Quiz app for a school project. It's meant to ask the user how many questions they want, and they then enter all of the Q&A's. Once finished, someone will then take the test.

The problem is, I'm getting an IndexError from the results function. This function is supposed to compare the test answers with the user's answers and print out a score.

def results(testAnswers, userAnswers):
    score = 0
    for i in range(0, len(answers)):
        if testAnswers[i].lower().strip() == userAnswers[i].lower().strip():
            score += 1

    print("\nResults: You got " + str(score) + " out of " + str(len(answers)) + "!")

Does anyone know how I can fix this problem?

Upvotes: 0

Views: 2811

Answers (3)

Jonty Morris
Jonty Morris

Reputation: 807

Due to an unknown reason, the testAnswers and userAnswers weren't in equal length. The lesson here is to always make sure they are the same length.

A simple if-statment can prevent the entire error.

if len(answers) != len(userAnswers):
    return

Upvotes: 0

garyboland
garyboland

Reputation: 135

Perhaps copying your code into this site went wrong, but regardless the code is not correctly formatted here which makes it very difficult to read.

regardless, its clear that you are indexing into a list to a point that doesn't exist. to help track down this error, add this line after you start your while loop:

print 'n %s, times %s, user_answers %s, answer_list %s' % (n, times, user_answers, answer_list)

then run the program and paste the output of the program into your question (but first please correct the indenting)

Upvotes: 0

karthikr
karthikr

Reputation: 99680

Your problem is here:

while n < times:
    if user_answers[n] == answer_list[n]:
        score += 1
        n += 1
    if user_answers[n] != answer_list[n]:
        n += 1

Lets say times is 10, and n is 9, it executes, and n+=1 makes it 10. Most likely, you have 10 elements in the array (note 10 is an example), and now user_answers[10 raises an exception, as the valid varles are 0..9

To fix this issue, use elif:

while n < times:
    if user_answers[n] == answer_list[n]:
        score += 1
        n += 1
    elif user_answers[n] != answer_list[n]:
        n += 1

Alternate approach is to get rid of the else clause altogether,

while n < times:
    if user_answers[n] == answer_list[n]:
        score += 1
    n += 1

Note that there are quite a few places you could optimize the code, but I am just going to leave the answer here, and let you figure other things out yourself.

Upvotes: 3

Related Questions