Python多选题代码出现IndexError: list index out of range错误求助
问题解决:IndexError: 列表索引超出范围
错误原因
question_prompts列表中的三个字符串未用逗号分隔,Python会自动将相邻的字符串字面量拼接成一个字符串,导致该列表实际仅包含1个元素,尝试访问索引1和2时自然触发索引越界错误。
修正后的代码
Question.py(无需修改)
class Question: def __init__(self, prompt, answer): self.prompt = prompt self.answer = answer
student.py(修正列表元素分隔及输出格式)
from Question import Question question_prompts = [ 'what color are apples?\n(a) red\n(b) purple\n(c) orange\n\n', 'what color are bananas?\n(a) teal\n(b) black\n(c) yellow\n\n', 'what color are oranges?\n(a) white\n(b) orange\n(c) red\n\n' ] questions = [ Question(question_prompts[0], 'a'), Question(question_prompts[1], 'c'), Question(question_prompts[2], 'b'), ] def run_test(questions): score = 0 for question in questions: answer = input(question.prompt) if answer == question.answer: score += 1 print('you got ' + str(score) + '/' + str(len(questions)) + ' correct') run_test(questions)
注:顺便修正了打印语句中correct前缺失的空格,避免输出格式不规范。
内容的提问来源于stack exchange,提问作者Manly Toaster
相关产品推荐
相关产品推荐

