lundi 6 novembre 2017

How To Use A Line In A File In An If Statement In Python

So I'm trying to make a code that has questions and answers stored in a text file and it calls the line with the question on it and then you input an answer and if it matches the line with the answer on it it prints 'correct' but if not it prints 'wrong'.

I can't seem to figure out the second part.

file = open("test2.txt", "w")
file.write("When was the Battle of Hastings? 1066 or 1088.")
file.write(str(1066))
file.close()
file = open("test.txt", "r")
for line in file:
    sec=line.split(".")
print(sec[0])
file.close()

answer = input ("Type your answer: ")
if answer == (sec[1]):
    print ("Correct!")
else:
    print ("Wrong it's 1066.")

It just tells me I'm wrong even when I type in the correct answer. I've also tried:

file.write(1066)

and

file.write("1066")

but I am currently settled on

file.write(str(1066))

Aucun commentaire:

Enregistrer un commentaire