Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python写文件数学生成器_Python - Fatal编程技术网

Python写文件数学生成器

Python写文件数学生成器,python,Python,您好,我有一个随机数学测验的代码,我想它保存的名称和有分数旁边的文件,我想它保留的数据,而不是写在它的每一次可以有人请帮助我,并添加在我想它,所以它可以像这样重新录制,让我说,我玩了它,我希望该文件是这样的,然后如果其他人参加了测验,它只是把名字添加到列表中,而不是先删除列表 姓名分数 def quiz(): import random import time name=input("What is your name?") print ("Alright",n

您好,我有一个随机数学测验的代码,我想它保存的名称和有分数旁边的文件,我想它保留的数据,而不是写在它的每一次可以有人请帮助我,并添加在我想它,所以它可以像这样重新录制,让我说,我玩了它,我希望该文件是这样的,然后如果其他人参加了测验,它只是把名字添加到列表中,而不是先删除列表

姓名分数

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()
改变

f = open('results.txt','w')

读取文件I/O的python文档。
'w'
覆盖现有文件

如果你想要名字和分数

f.write('{} : {}\n'.format(name, score) )

f=open('results.txt','a')
好的,谢谢你添加了,有没有办法让它转到一个新的行而不是它旁边的行?我如何才能在其中添加名称呢?还有,使用
writeln
而不是
write
,来添加名称,和你对分数做的一样。@DannyBradshaw如果我的解决方案是你想要的,请选择它作为你的答案,这样它就可以接近了。谢谢你,这很有效,有没有办法让它每次都换一行只要在
中添加一个
\n
。写

f.write('{} : {}\n'.format(name, score) )