Dylan Evans Dylan Evans - 3 years ago 150
Python Question

Trouble using Equality operator to check if a user input is the same as a line from a text file in Python

Just started to learn Python again since finishing my GCSEs two years ago. I've got a bit of background in C# but am having difficulties making a simple program work.

The program is a quiz. It takes input from a text file and stores each line into a variable. Then the program goes on to take input in the form of an answer however when I enter the correct answer to the question,the equality operator does not recognise the user input and line from the text file as the same.

The textfile is formatted through Question on first line, answer on second and so on.

Heres what I have so far:

quiz = open("cseasy.txt","r")

wholequiz = quiz.readlines()

q1 = wholequiz[0]

a1 = wholequiz[1]

mark = 0

ua1 = input(q1)

print (ua1)


if a1 == ua1:

print ("Correct!")

mark = mark + 1


print ("Incorrect!")

I'd be grateful for any solutions and why the current program is not producing the result I want.

The above answer to q1 is A, yet when I enter "A" the output of the program is "Incorrect!".

Answer Source


wholequiz = quiz.readlines()

you get a list of lines with newline (\n) at the end. The comparison cannot succeed unless you do:

a1 = wholequiz[1].rstrip()

That method is useful when you're reading line by line, but since you're reading the whole file at once, you could also do:

wholequiz = quiz.read().splitlines()

then no need to strip for linefeed. Of course, if there's a trailing space in the file that won't remove it (the rstrip method does)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download