【发布时间】:2021-02-27 20:18:41
【问题描述】:
我对编码有点陌生。我正在做一个测验,我从 csv 文件中读取问题。我不明白为什么我的代码不会打印“正确。做得好”。当用户输入正确答案时。相反,它总是打印“不正确”。我已经确定userInput 和打印出来的答案是一样的。
FILENAME = 'quiztest.csv'
def welcomeUser():
name = input("Hello. Please enter your name: ")
print("Welcome " + name + "!")
def readFile():
with open(FILENAME, "r") as file:
for line in file:
line = line.split(",")
question = line[0]
options = line[1]
answer = line[2]
askQuestion(question, options, answer)
def askQuestion(question, options, answer):
print(question)
print(options)
userInput = input("Please enter the answer: ")
print(userInput)
print(answer)
if userInput == answer:
print("Correct. Well Done.")
else:
print("Incorrect.")
readFile()
返回什么:
What is my name?
Tom Jeff Fred Sam
Please enter the answer: Sam
Sam
Sam
Incorrect.
【问题讨论】:
-
@JonathonReinhart 不,换行符不包含在
input返回的字符串中。 -
但如果答案是该行的最后一部分,那么它包含一个。所以,变化应该是
answer = line[2].strip()。 -
@CODER123456789,请注意minimal reproducible example 指南——理想情况下,问题应该有在不更改运行时复制特定问题的最短程序。我们不需要您的整个测验程序;只是从文件中读取一行并将字符串与其进行比较的东西。 (您可以尝试对文件中的行进行硬编码,看看是否可以解决错误,然后尝试从用户输入中对行进行硬编码,看看是否那个 i> 解决了这个错误,尝试这两件事的过程可以帮助你提出一个狭窄的问题,或者给你足够的提示来自己解决它)。
-
@Thierry Err,哎呀。谢谢,删除了我的评论。
标签: python