Search code examples
loopspython-3.xnotepadscoring

Having problems with a scoring loop by reading from a text file


I am new to python and creating a quiz program. I have the questions and answers to the quiz on separate text files.

The text file for answers are all in lower case so I don't believe that the .lower() is the problem.

Here is my following code:

#Programming exercise-Writing to files

question_file = open("Quiz.txt","r")
answer_file = open("QuizAnswers.txt","r")


print("Welcome to the ScienceQuiz!")

question = question_file.readlines()

answer = answer_file.readlines()

score = 0

i = 0

for i in range(20):
    print(question[i])
    user_input = input("Enter your answer: ")
    user_input = user_input.lower()
    if user_input == answer[i]:
        score = score + 1
    else:
        score = score

print("\nYou scored: ",score,"/20")

At the end of the game even though all answers that I inputted were right it prints that I got 0/20?


Solution

  • The problem you are experiencing is quite a common issue when reading lines from text files. When you read a line from a text file, provided it is formatted like this:

        line one
        line two
        line three
        [empty line]
    

    Each element of the list will be formatted like line one\n or line two\n as \n is the carriage return character for many systems. When you type the answer in your python program you would type just line one so when Python tries to literally compare the two, for obvious reasons it returns that they were different.

    There are two solutions to this problem:

    1. Add

      for i in range(len(answer)):
          answer[i] = answer[i][:-1]
      

      immediately after your:

      answer = answer_file.readlines()
      

      and it will remove the last character \n from each element. This would be the more commonly used solution.

    2. Add \n to the user input:

      user_input = input("Enter your answer: ") + "\n"
      

    Both solutions require that the last line of your QuizAnswers.txt be an empty line and nothing more. Your QuizQuestions.txt will also have \n on the end of every line, meaning that printing them out will cause a seemingly inexplicable line break to also be output. You must use the [:-1] solution by looping through the questions to fix this.

    Hope this helped,

    Apples