linecache 在 if 语句中不起作用?
linecache doesn't work in an if statement?
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")
无论如何,它打印"wrong"。我正在做一个测验,需要能够从文件中读取问题和答案。 for 循环只是重复每个问题和答案的代码。问题和答案也是相同的,这可以通过打印命令看到(例如,如果其中一个问题是 2+2 而我输出 4,它会说答案是 4 并且答案是 4)。我对问题和答案使用了相同的文件,并且将每个文件分别存储在单独的一行中。
看来answer
的末尾有一个换行符(\n
);我们必须去掉它:
answer = linecache.getline("looptestofreceivinganswers.txt", linea).rstrip('\n')
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")
无论如何,它打印"wrong"。我正在做一个测验,需要能够从文件中读取问题和答案。 for 循环只是重复每个问题和答案的代码。问题和答案也是相同的,这可以通过打印命令看到(例如,如果其中一个问题是 2+2 而我输出 4,它会说答案是 4 并且答案是 4)。我对问题和答案使用了相同的文件,并且将每个文件分别存储在单独的一行中。
看来answer
的末尾有一个换行符(\n
);我们必须去掉它:
answer = linecache.getline("looptestofreceivinganswers.txt", linea).rstrip('\n')