0
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)。我对问题和答案都使用了相同的文件,并且我将每个文件分别存储在单独的行中。

4

1 回答 1

0

它的末尾似乎answer有一个换行符( );\n我们必须去掉它:

answer = linecache.getline("looptestofreceivinganswers.txt", linea).rstrip('\n')
于 2017-11-26T17:50:21.663 回答