Search code examples
pythonlinecache

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")

No matter what, it prints"wrong". I'm making a quiz that needs to be able to read questions and answers from a file. the for loop just repeats the code for each question and answer. Also the question and answer are the same, which is seen by the print commands (e.g if one of the questions is 2+2 and I output 4, it will say that the answer is 4 and that the answer is 4). I've used the same file for both the questions and answers and I have each respective one stored on a separate line.


Solution

  • It appears that answer has a newline character (\n) on the end of it; we'd have to strip that:

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