【问题标题】:linecache doesn't work in an if statement?linecache 在 if 语句中不起作用?
【发布时间】: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 是正确的,看看我的回答。

标签: python linecache


【解决方案1】:

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

answer = linecache.getline("looptestofreceivinganswers.txt", linea).rstrip('\n')

【讨论】:

  • 很高兴为您提供帮助,欢迎来到 Stack Overflow。如果此答案或任何其他答案解决了您的问题,请将其标记为已接受。
猜你喜欢
  • 2017-05-22
  • 1970-01-01
  • 2012-07-16
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 2015-05-12
  • 2016-04-25
  • 1970-01-01
相关资源
最近更新 更多