0

I am trying to make a sort of quiz revision code for my exams. I am however struggling to get the selection for whether the answer is right or not to work. no matter what answer I put it outputs "nope". Each file I use has 6 lines. import random

file = open("questions.txt", "r")
questions = file.readlines()

file2 = open("answers.txt", "r")
answers = file2.readlines()

question_answering = True

while question_answering:
    question = random.randrange(5)
    print(questions[question])
    answer = input("enter your answer: ")
    print(answers[question])
    if answer == answers[question]:
        print("well done!")
    else:
        print("nope")

I have included a test which is print(answers[question]) which does output the correct answer that I am looking for but when I input that answer it does not work.

J.Fitz
  • 107
  • 4
  • Possible duplicate of [Reading a file without newlines](https://stackoverflow.com/questions/12330522/reading-a-file-without-newlines) – Aran-Fey Feb 02 '18 at 10:37

1 Answers1

2

Probably because the answers read from the file still have newlines on them, and your input does not. Strip the newlines off the read answers and it should work.

Newlines (often '\n' or '\r' or a combination thereof, depending on the context) are characters that tell the computer to, well, move to the next line. When you read a file, you often split the lines on the newline character, but whether or not the newline is retained with the line of text is going to be language/library specific. As you can see in the link I included, readLines() retains the newline characters. So you need to remove them to get the answer by itself (without the newline character).

Reading a file without newlines

Doug
  • 644
  • 1
  • 6
  • 22
  • This did work and was the problem. However from what I read I don't quite understand it. all I know is it works. If you can explain to me the term "newlines" that would be great thanks. – J.Fitz Feb 02 '18 at 10:40
  • @J.Fitz Please mark your question as answered by clicking the **tick** button below the score of Doug's answer! – Ubdus Samad Feb 02 '18 at 10:47