Using Python to make a quiz from a text file

Question:

I’m learning Python, and I need to make a mini quiz. The questions and answers are in a text file (called textfile.txt), each on its own line. At the end of the quiz, it will tell the user their score out of three.

I can get my quiz to print out the first question, and when I try inputting an answer no matter what I put (correct answer or incorrect answer), it’ll tell me it’s incorrect.

In the text file I have the following:

whats 1+1
2
whats 2+2
4
whats 3+3
6

And here is what I have in my .py file:

questions = open("textfile.txt", "r")
content = questions.readlines()

userScore = 0

for i in range(1):
   print(content[0])   
   answer = input("What's the answer: ")
   if answer == content[1]:
      print("Correct")
      userScore + 1
   else:
      print("Incorrect")
  
   print(content[2])
   answer = input("What's the answer: ")
   if answer == content[3]:
      print("Correct")
      userScore + 1
   else:
      print("Incorrect")
   print(content[4])
  
   answer = input("What's the answer: ")
   if answer == content[5]:
      print("Correct")
      userScore + 1
   else:
      print("Incorrect")
questions.close()

print("You're done the quiz, your score is: ")
print(userScore)

How do I make it read the correct answer and keep track of the users score?

Asked By: Shub

||

Answers:

If you really wrote this code yourself you would realise that you need to set the users score to 0 before the loop and increment or decrement when you print correct or incorrect, most people on stackovwrflow will not tell you the answer, they will at least help you learn by having you reasearch a little.

Answered By: Ico Twilight

First of all, use .strip() to remove the newline characters. The answers comparison might not always work because of them.

To ask every even row you can use the modulo (%) operator to get the remainder of the current line index after dividing it by two.

If the answer is correct we add 1 to the corrent_answer_count variable that we print in the end.

questions = open(r"textfile.txt", "r")
content = [line.strip() for line in questions.readlines()]
questions.close()

corrent_answer_count = 0
for i in range((len(content))):
    if i % 2 == 0:
        print(content[i])
        answer = input("What's the answer: ")
        if answer == content[i + 1]:
            print("Correct")
            corrent_answer_count += 1
        else:
            print("Incorrect")

print("Correct answer count: " + str(corrent_answer_count))
Answered By: CaptainCsaba
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.