首页 > 解决方案 > 代码不检查输入的答案是否正确

问题描述

我正在尝试创建一个多项选择测验,该测验从外部 .txt 文件中提取问题并将其打印在 python 中。文本文件的布局如下:

1、谁是第一个在月球上行走的人?,A.迈克尔·杰克逊,B.巴斯光年,C.尼尔·阿姆斯特朗,D.Nobody,C

当我运行代码并输入正确答案时,它仍然显示不正确,但继续说出我输入的答案。

在代码中,我将文本文件中的每一行都用“,”分隔,因此文本文件中的正确答案始终是 detail[6]。在我放的代码中:

if answer.upper() == detail[6]:
            print("Well done, that's correct!")
            score=score + 1
            print(score)
elif answer.upper() != detail[6]:
            print("Incorrect, the correct answer is ",detail[6])
            print(score)

我认为这会起作用,因为它会根据详细信息 [6] 检查输入的答案,但结果总是不正确。

import random
score=0
with open('space_quiz_test.txt') as f:
    quiz = f.readlines()
questions = random.sample(quiz, 10)    
for question in questions:
    detail = question.split(",")
    print(detail[0],detail[1],detail[2],detail[3],detail[4],detail[5])
    print(" ")
    answer=input("Answer: ")
    while True:
            if answer.upper() not in ('A','B','C','D'):
                print("Answer not valid, try again")
            else:
                break
    if answer.upper() == detail[6]:
        print("Well done, that's correct!")
        score=score + 1
        print(score)
    elif answer.upper() != detail[6]:
        print("Incorrect, the correct answer is ",detail[6])
        print(score)

我希望代码能够通过检查文本文件中的详细信息 [6] 来检查输入的答案是否正确,而不是总是显示不正确,正确的答案是详细信息 [6]。

标签: python-3.x

解决方案


问题是readlines()在每行末尾保留换行符。你detail[6]是类似的东西,'C\n'而不是'C'它自己。要解决这个问题,请使用

detail = question.strip().split(",")

推荐阅读