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. 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个字符。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.