Jonty Morris
Jonty Morris

Reputation: 807

Error: list index out of range?

So I've been trying to make a python app. It asks the user how many quiz questions they want and then they go through and type the questions and answers and then someone has to answer them ext. The actual error I'm getting is in the results.

note- The def's have 8 spaces so it can make a code block

from time import sleep


def results():
    n = 0
    score = 0
    while n <= times:
        if user_answers[n] is answer_list[n]:
            score += 1
            n += 1
        if user_answers[n] != answer_list[n]:
            n += 1
    if n > times:
        print(" ")
        print("Results-")
        print("You got:", score, "Correct")
        sleep(4)
        main()

def quiz():
    print(" ")
    global user_answers
    user_answers = []
    number = 0
    n1 = 1
    while n1 <= times:
        print(" ")
        print("Question: " + array_list[number])
        user_answers.append(input("Answer: "))
        n1 += 1
        number += 1
    if n1 > times:
        results()

def answers():
    print(" ")
    print("Great, now you will need to enter\nall of the answers!")
    sleep(4)
    global answer_list
    answer_list = []
    n1 = 1
    number = 0
    while n1 <= times:
        print(" ")
        print("Question: " + array_list[number])
        answer_list.append(input("Real Answer: "))
        n1 += 1
        number += 1
    if n1 > times:
        print(" ")
        print("Perfect, now have fun with your quiz!")
        print("--------------------------------------")
        sleep(4)
        quiz()

def main():
    print("----------------------------------------")
    print("Enter the number of questions you want")
    global times
    times = int(input("Number: "))
    n1 = 1
    global array_list
    array_list = []
    print(" ")
    print("Now enter the Questions")
    print(" ")
    while n1 <= times:
        array_list.append(input("Question: "))
        n1 += 1
    if n1 > times:
        answers()

main()

here is the error I'm getting-

    Traceback (most recent call last):
    File "/Users/isabella/Desktop/programming/Python coding/quiz /testing.py", line 160, in <module>
    main()
    File "/Users/isabella/Desktop/programming/Python coding/quiz /testing.py", line 157, in main
    answers()
    File "/Users/isabella/Desktop/programming/Python coding/quiz /testing.py", line 139, in answers
    quiz()
    File "/Users/isabella/Desktop/programming/Python coding/quiz /testing.py", line 117, in quiz
    results()
    File "/Users/isabella/Desktop/programming/Python coding/quiz /testing.py", line 8, in results
    if user_answers[n] == answer_list[n]:
    IndexError: list index out of range

Upvotes: 0

Views: 66

Answers (1)

timrau
timrau

Reputation: 23058

while n <= times:

Python's legal list index is [0, n-1] instead of [0, n]. Thus it should be while n < times:.

Upvotes: 2

Related Questions