元组索引超出范围?蟒蛇 3.4.2.



我正在用python创建一个csv文件测验,在测验结束时到达摘要之前一切都很好。

percentage = (correctScore * 100) / 20
print("Alright now, lets see how you did... ")
time.sleep(2)
if correctScore == 20:
    print("Excellent work there, (yourNameIs), you scored 100%. ")
elif correctScore >= 11 <= 19:
    print("Well done", yourNameIs, "you passed. You scored", percentage,"%. You got {} question(s) wrong".format(len(incorrect)))
    for question, user_answer in incorrect:
        print("Q{}: {}".format(data[question][0]))
        print("tYou answered {}. The correct answer is {}".format(user_answer, data[question][5]))
elif correctScore >= 5 <= 10:
    print("Good effort", yourNameIs, "you scored", percentage,"%. You got {} question(s) wrong".format(len(incorrect)))
    for question, user_answer in incorrect:
        print("Q{}: {}".format(data[question][0]))
        print("tYou answered {}. The correct answer is {}".format(user_answer, data[question][5]))
else:
    print("You need to try harder next time", yourNameIs, "you scored", percentage,"%. You got {} question(s) wrong".format(len(incorrect)))
    for question, user_answer in incorrect:
        print("Q{}: {}".format(data[question][0]))
        print("tYou answered {}. The correct answer is {}".format(user_answer, data[question][5]))

获得百分比后,我收到错误

print("Q{0}: {1}".format(data[question][0]))
IndexError: tuple index out of range

有什么想法吗?

correctScore = 0 
incorrect = [] 
question = data[recordnum-1][0] 
a = data[recordnum-1][1] 
b = data[recordnum-1][2] 
c = data[recordnum-1][3] 
d = data[recordnum-1][4] 
answer = data[recordnum-1][5] –

你在格式字符串中使用了两个{},但只传递一个参数,python需要两个参数来格式化,所以你得到IndexError: tuple index out of range

print("Q{0}: {1}".format(data[question][0]))  
        ^^    ^^

如果data[question]有两个元素,你可以用*解压缩:

print("Q{0}: {1}".format(*data[question]))

无论哪种方式,您都需要传递两个参数。

最新更新