2015-10-23 50 views
0

我正在为数学测验编写代码,在这个测验中,我需要能够将数据存储到文本文件。数据是测验结束时的分数。我需要它输出到像这样的文本文件...Python存储数据,高分

> 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

什么不按预期工作? – ppperry

+0

你在哪里/如何定义名字和得分?我建议在输入数据前敲定数据 –

+0

它输出的很好,但它需要像上面显示的那样输出csv样式,我只是不知道该怎么做 –

回答

2

你在找什么的关键核心是:

fi.writelines("\n"+name+","+ ",".join([str(score) for score in scores]) 

但目前还不清楚你如何让你的score值,那么你将如何正确引用scores,目前尚不清楚。