简体   繁体   English

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

[英]Python error message: builtins.IndexError: string index out of range

I am creating a game where the program will read from a file that contains 5 multiple choice questions and the user can answer this questions and receive a score. 我正在创建一个游戏,程序将从包含5个多项选择题的文件中读取内容,用户可以回答此问题并获得分数。 However I am getting stuck as I get the same error message: 但是,当我收到相同的错误消息时,我被卡住了:

builtins.IndexError: string index out of range

here is my code so far: 到目前为止,这是我的代码:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 builtins.IndexError:列表索引超出范围 pygame animation - builtins.IndexError: list index out of range pygame animation 如何解决此错误:“builtins.IndexError: list index out of range”? - How can I solve this error: “builtins.IndexError: list index out of range”? Python错误:“ IndexError:字符串索引超出范围” - Python error:“IndexError: string index out of range” Python错误:IndexError:字符串索引超出范围 - Python Error: IndexError: string index out of range Python 错误:“IndexError:字符串索引超出范围” - Python error: “IndexError: string index out of range” Flask 有时会正常工作,有时会导致“builtins.IndexError”错误? - Flask sometimes works properly and sometimes causes "builtins.IndexError" error? 如何解决python中的“ IndexError:字符串索引超出范围”错误? - How to resolve “IndexError: string index out of range” error in python? 如何修复Python中的“ IndexError:字符串索引超出范围”错误 - How to fix “IndexError: string index out of range” error in python Python 错误:IndexError:字符串索引超出家谱程序范围 - Python Error: IndexError: string index out of range for a Family Tree Program 如何解决python中的以下错误:“ IndexError:字符串索引超出范围” - How to solve the following error in python: “IndexError: string index out of range”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM