我对编码有点陌生。我正在做一个测验,我从csv文件中阅读问题。我不明白为什么我的代码不会打印"正确"。做得好!"当用户输入正确答案时。相反,它总是打印"Incorrect."我已经通过打印它们来确保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.
注意最后一个"one_answers"不正确";在你的输出中。answer
中的值包含一个换行符,因为它是您从输入文件中读取的行的最后一部分,并且您读取该文件的方式,您在处理的每行末尾都得到一个换行符。
你的问题很容易解决。只需调用strip()
来剥离从输入文件中读取的输入行末尾的换行符:
def readFile():
with open(FILENAME, "r") as file:
for line in file:
line = line.strip().split(",")
question = line[0]
options = line[1]
answer = line[2]
askQuestion(question, options, answer)