如何将多个分数附加到同一行?

时间:2015-03-15 13:30:00

标签: python append

我已经设置了一个任务,我有一个数学测验,学生需要三次,然后他们的分数被保存到.txt文件。我遇到的问题是,因为他们必须进行3次测验,这个名字是'变量每次都被重置,它们的分数保存到文本文件中的三个单独的行。我怎样才能让程序识别出该人之前是否已经玩过并将该分数保存到文本文件中的同一行?

在创建的文本文件中,它目前看起来像这样 -

Tom , 10
Tom , 5
Tom , 3

我怎样才能得到它?

Tom , 10 , 5 , 3

我的测验代码:

import time

print ('What is your name?')
name = input()
print (' Hello ' + name +', Welcome to the python maths quiz, you will be asked 10 maths questions and marked out of 10 at the end, good luck! ')
time.sleep (1)
Class=input("Which class are you in? 1,2 or 3?")

import random

score = 0
for x in range (10):
    ops = ['+', '-', '*']
    num1 = random.randint(1,10)
    num2 = random.randint(1,10)
    op = random.choice(ops)
    question = '{} {} {}?'.format(num1, op, num2)
    print ('What is '+ question + '?')
    answer = input()

    if op is ("+") :
        rightanswer = num1+num2
        if answer == str(rightanswer):
            print('Well done, that is correct')
            score = score + 1
        else:
            print('Wrong, the correct answer was',rightanswer,'!')

    if op is ("-") :
        rightanswer = num1-num2    
        if answer == str(rightanswer):
            print('Well done, that is correct')
            score = score + 1
        else:
            print('Wrong, the correct answer was',rightanswer,'!')

    elif op is ("*") :
        rightanswer = num1*num2
        if answer == str(rightanswer):
            print('Well done, that is correct')
            score = score + 1
        else:
            print('Wrong, the correct answer was',rightanswer,'!')



print ("Well done " + name + "! You scored " , score,"out of 10")

if Class=="1" :
    my_file=open('Class1.txt','a')
    my_file.write(name)
    my_file.write(' , ')
    my_file.write(str(score))
    my_file.write('\n')
    my_file.close()

elif Class=="2" :
    my_file=open('Class2.txt','a')
    my_file.write(name)
    my_file.write(' , ')
    my_file.write(str(score))
    my_file.write('\n')
    my_file.close()

else :
    my_file=open('Class3.txt','a')
    my_file.write(name)
    my_file.write(' , ')
    my_file.write(str(score))
    my_file.write('\n')
    my_file.close()

1 个答案:

答案 0 :(得分:0)

这有点像人们被抓住的标准错误。您的代码的最后一部分需要被替换,而不是代码向下,代码行向下,例如我的项目中的示例和示例

enter code here
if usersClass == "1":
    with open("class1.txt","a+") as f:
        f.write("{}:Scored {} in {} seconds".format(username,correctAnswers,timeTaken))

所以你要做的就是重新指导/转换它以适应并包含你的逗号。