你好,我有一个随机数学测验的代码,我希望它保存名称,并在文件旁边有分数,我希望它保留数据,而不是每次都可以写一个人请帮助我并添加这在我想它所以它可以像这样重新说它我说我玩它我希望文件是这样然后如果有人参加测验它只是添加名称列表不首先删除列表
名称分数
def quiz():
import random
import time
name=input("What is your name?")
print ("Alright",name,"Welcome to your maths quiz")
score=0
question=0
for question in range (1,11):
ops=['*','+','-']
rand=random.randint(1,10)
rand2=random.randint(1,10)
operation=random.choice(ops)
maths = eval(str(rand) + operation + str(rand2))
print ("Question",question)
time.sleep(0.5)
print (rand,operation,rand2)
question=question+1
d=int(input ("What is your answer:"))
if d==maths:
print ("Correct")
score=score+1
else:
print ("Incorrect. The actual answer is",maths)
if score >=7:
print ("Well done you got",score,"out of 10")
else:
print ("Unlucky you got",score,"out of 10")
percentage=score/10*100
print ("You got",percentage,"%")
f = open('results.txt','w')
f.write('%d' % score)
f.close()
playagain = 'yes'
while playagain == 'yes':
quiz()
print('Do you want to play again? (yes or no)')
playagain = input()
答案 0 :(得分:0)
更改
f = open('results.txt','w')
到
f = open('results.txt','a')
阅读文件I / O的python文档。 'w'
会覆盖现有文件
如果您想要带分数的名称
f.write('{} : {}\n'.format(name, score) )