2015-10-23 47 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,目前尚不清楚。