Python错误消息:builtins.IndexError:字符串索引超出范围

时间:2011-11-10 03:07:02

标签: python

我正在创建一个游戏,程序将从包含5个多项选择题的文件中读取,用户可以回答这些问题并获得分数。但是,当我得到相同的错误消息时,我会卡住:

builtins.IndexError: string index out of range

到目前为止,这是我的代码:

def main():
    playagain = True
    while playagain:
        inFile = open('Questions.txt', 'r')
        condition = True
        while condition:
            for line in range(5):
                line = inFile.readline()
                print(line)

            anskey = inFile.readline()
            anskey = anskey[4]

            status = True
            while status:
                useranswer = str(input('Enter your answer?  '))
                useranswer = useranswer.upper()

                if useranswer == 'A' or useranswer == 'B' or useranswer \
                    == 'C' or useranswer == 'D':
                    status = False
                    if useranswer == anskey:
                        correct = correct + 1
                        print('Correct Answer!')
                    else:
                        print('Wrong Answer!')
                        correct = correct
                else:
                    print('Answer not valid!')


main()

1 个答案:

答案 0 :(得分:0)

由于代码中只有一个索引操作,anskey[4],我的猜测是你的inFile有一行少于5个字符的行。