我正在编写数学测验的代码,在这个测验中,我需要能够将数据存储到文本文件中。数据是测验结束时的分数。我需要它输出到像这样的文本文件...
> Tom,4,5,7
> Evie,6,10,8
到目前为止我只有这个
import random
Class=input("What class are you in?")
name=input("What is your name?")
print("Welcome to the maths quiz",name)
print("Try to answer all the questions with the correct number.")
score=0
questionnumber=0
while questionnumber<10:
Number1=random.randrange(1,10)
Number2=random.randrange(1,10)
Operation=random.randrange(1,4)
if(Operation==1):
symbol= " + "
correctAnswer = Number1 + Number2
elif(Operation==2):
symbol= " - "
correctAnswer = Number1 - Number2
else:
symbol= " * "
correctAnswer = Number1 * Number2
question=(str(Number1)+str(symbol)+str(Number2)+"=?")
useranswer=(float(input(question)))
if useranswer==correctAnswer:
score=score+1
print("Well Done, Correct. Your score is now ",score,"/10")
questionnumber=questionnumber+1
else:
print("Incorrect, sorry. Score:",score)
questionnumber=questionnumber+1
else:
print(name," you finished with a score of ",score,"/10")
if(Class==1):
fi=open("Class1.txt","a")
fi.writelines("\n"+name+":"+str(score))
fi.close
elif (Class== 2):
fi=open("Class2.txt","a")
fi.writelines("\n"+name+":"+str(score))
fi.close
elif (Class== 3):
fi=open("Class3.txt","a")
fi.writelines("\n"+name+":"+str(score))
fi.close
输出看起来像这样......
Tom:4
Tom:5
Tom:7
Evie:6
Evie:10
Evie:8
任何帮助都将不胜感激。
答案 0 :(得分:2)
您正在寻找的重要核心是:
fi.writelines("\n"+name+","+ ",".join([str(score) for score in scores])
但目前还不清楚您是如何获得score
值的,因此不清楚如何正确引用scores
。