首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在if语句中,linecache不工作?

在if语句中,linecache不工作?
EN

Stack Overflow用户
提问于 2017-11-26 17:39:16
回答 1查看 60关注 0票数 0
代码语言:javascript
复制
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)。对于问题和答案,我都使用了相同的文件,并且每个文件都存储在单独的行中。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-26 17:50:21

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

代码语言:javascript
复制
answer = linecache.getline("looptestofreceivinganswers.txt", linea).rstrip('\n')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47499083

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档