I am creating a quiz program with python. There are three text files, one for outputting the question (works), one for checking if the user input the correct (works) and one for updating mastery. The latter isn't working. A question is mastered when is answered correct three times. I want to update the mastery from the text file to go from zero to one (and so on).
When I run my program it replaces the first line with 1, however the two 0's below it go missing and I therefore recieve an index out of range error. I am open to trying other methods.
This is the code I am attempting to implement the code below into my own program:
with open('stats.txt', 'r') as file:
# read a list of lines into data
data = file.readlines()
print(data)
print("Your name: " + data[0])
x = "0"
# now change the 2nd line, note that you have to add a newline
data[1] = x + "\n"
# and write everything back
with open('stats.txt', 'w') as file:
file.writelines(data)
My program:
question_answered = 0 # sets number of questions answered to zero
lineq = 6 # sets the number of lines to output from questions.txt
linea = 0 # sets the number of linea to read from answers.txt
with open("questions.txt", "r") as q:
with open("answers.txt", "r") as a:
answer_lines = a.readlines()
while question_answered != 3:
question_answered += 1
for i in range(lineq):
line2 = (q.readline())
print(line2)
response = input("answer:")
if response not in answer_lines[linea]:
print("incorrect")
mastery = (update_mastery[linea])
mastery = int(mastery)
if mastery < 1:
print("mastery", mastery)
else:
mastery -= 1
print("mastery", mastery)
else:
print("correct")
with open("mastery.txt", "r") as m:
update_mastery = m.readlines()
mastery = update_mastery[linea]
mastery = int(mastery) + 1
mastery = str(mastery)
update_mastery[linea] = mastery + "\n"
with open('mastery.txt', 'w') as m:
m.writelines(update_mastery[linea])
linea += 1
questions()
questions.txt:
1)Define isotope
[A]Atoms of the same element with same number of protons and a different number of neutrons
[B]Atoms of the different element with same number of protons and a different number of neutrons
[C]Atoms of the same element with same number of neutrons and a different number of protons
[D]Atoms of the same element with same number of protons and a different number of electrons
2)Name the type of decay that occurs when, they have too many neutrons
[A]Gamma Radiation
[B]Alpha Decay
[C]Beta Plus Decay
[D]Beta Minus Decay
3)Define Coulomb
[A]1 coulomb is the quantity of charge carried past a given point if a steady current of 1 amp flows for 1 second
[B]1 coulomb is the quantity of charge carried past a given point if a steady voltage of 1 volts per 1 second
[C]1 coulomb is the quantity of current carried past a given point if a steady voltage of 1 volts per 1 second
[D]1 coulomb is the rate of flow of charge
answers.txt:
A
D
A
mastery.txt:
0
0
0
fileinputmodule can help