【发布时间】:2017-11-26 17:39:16
【问题描述】:
import linecache
for i in range (4):
file = open("looptestofreceivingquestions.txt", "r")
lineq = i+1
print(linecache.getline("looptestofreceivingquestions.txt", lineq))#gets line q depending on iteration
question = input("what is the answer?")
linea = i+5
answer = linecache.getline("looptestofreceivinganswers.txt", linea)
file.close()
print(question)
print(answer)
if question == answer:
print("correct")
elif question != answer:
print("wrong")
无论如何,它都会打印“错误”。我正在做一个需要能够从文件中读取问题和答案的测验。 for 循环只是重复每个问题和答案的代码。问题和答案也是相同的,这可以通过打印命令看到(例如,如果其中一个问题是 2+2 并且我输出 4,它会说答案是 4 并且答案是 4)。我对问题和答案都使用了相同的文件,并且我将每个文件分别存储在单独的行中。
【问题讨论】:
-
print(answer)行上打印了什么?甚至可以使用print(repr(question))和print(repr(answer))来查看确切的差异。 -
也许
answer在末尾保留了一个换行符(当你打印它们时你应该注意到了)。 -
@Sebastian 我明白了:> 1+1=?答案是什么?2 '2' '2\n' 错了 2+2=?答案是什么?
-
@Sebastian 据我了解,问题是“2”,答案是“2\n”
-
看起来@JohnGordon 是正确的,看看我的回答。