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)。我在问题和答案中都使用了相同的文件,并且我将每个文件存储在一个单独的行中。
答案 0 :(得分:0)
answer
似乎在其末尾有换行符(\n
);我们不得不剥离:
answer = linecache.getline("looptestofreceivinganswers.txt", linea).rstrip('\n')