Grace
Grace

Reputation: 43

How to strip newline in string from readline() function?

For some reason the code won't increase the score when a correct answer is entered. It is a multiple choice quiz and so that is why it asks for entry of the correct letter for the answer. I have checked and there is nothing wrong with the answer or userAnswer variables but even when they both match, the score value doesn't increase by 1. MathQuiz.txt is a file that contains my questions and answers for the quiz. Does anyone know how to fix this? Thanks.
This is my code:

def questions():
    lol = open("MathQuiz.txt", 'r')
    score = 0

    for x in range(5):
        print(lol.readline())
        print(lol.readline())
        answer = lol.readline()
        userAnswer = input("Please chooose the letter correponding to your answer: ")
        while userAnswer.isspace() or userAnswer == "":
            print("You must enter a valid letter.")
            userAnswer = input("Please chooose the letter correponding to your answer: ")
        if answer == userAnswer:
            score += 1 
        else:
            score = score
        print(lol.readline())

    print("Your score is ", score)

questions()

The text file looks like this:

1.What is my name?

a)Grace b)Ellie c)Craig d)Veronica

d

2.What is my age?

a)12 b)18 c)45 d)15

a

3.Where do I live?

a)Birmingham b)London c)Leeds d)Scotland

c

4.What is my birthday?

a)6th May b)4th Jan c)12th August d)12th June

d

5.What is my favourite colour?

a)orange b)Red c)Blue d)Pink

c

[These answers are not correct - it's a random example]

Upvotes: 2

Views: 2757

Answers (1)

Grace
Grace

Reputation: 43

For anyone needing the answer to this, @rgk has let me know that

answer = lol.readline().strip()

is how to solve my problem :)

Upvotes: 1

Related Questions