python-3.x - 代码不检查输入的答案是否正确
问题描述
我正在尝试创建一个多项选择测验,该测验从外部 .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]。
解决方案
问题是readlines()
在每行末尾保留换行符。你detail[6]
是类似的东西,'C\n'
而不是'C'
它自己。要解决这个问题,请使用
detail = question.strip().split(",")
推荐阅读
- scala - Scala:在数据框中映射列整数值
- r - 有没有一种特定的方法可以使用 tidyr 将数据操作到可用的列中?
- php - 套接字连接关闭而未收到所有信息
- python - Python 请求 - 使用 TLS v.1_3
- python - 使用值作为列表和非空键创建新字典
- node.js - Sequelize findOrCreate 循环找不到新创建的行?
- unit-testing - 如何为同一方法命名不同的测试?
- sql - T-SQL:我可以让 APPLY 在 CTE 上运行 TVF 吗?
- django-models - 复杂模型的非平凡 django 序列化程序
- c# - ASP.NET Web 应用程序命名空间无法识别