错误:列表索引超出范围?

时间:2014-10-23 05:31:10

标签: python python-3.4

所以我一直试图制作一个python应用程序。它询问用户他们想要多少个测验问题,然后他们通过并输入问题和答案,然后有人必须回答它们。 我得到的实际错误在于结果。

注意 - def有8个空格,因此可以创建一个代码块

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()

这是我得到的错误 -

    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

1 个答案:

答案 0 :(得分:2)

while n <= times:

Python的合法列表索引是[0,n-1]而不是[0,n]。因此它应该是while n < times: