Python 如何将多个分数附加到同一行?
我被设置了一个任务,我有一个数学测验,学生们参加三次,然后他们的分数被保存到一个.txt文件中。我遇到的问题是,因为他们必须运行3次测验,“name”变量每次都会重置,他们的分数保存到文本文件中的三行。我如何才能得到它,以便程序识别该人是否曾经玩过,并将分数保存到文本文件中的同一行 在创建的文本文件中,当前看起来如下所示-Python 如何将多个分数附加到同一行?,python,append,Python,Append,我被设置了一个任务,我有一个数学测验,学生们参加三次,然后他们的分数被保存到一个.txt文件中。我遇到的问题是,因为他们必须运行3次测验,“name”变量每次都会重置,他们的分数保存到文本文件中的三行。我如何才能得到它,以便程序识别该人是否曾经玩过,并将分数保存到文本文件中的同一行 在创建的文本文件中,当前看起来如下所示- Tom , 10 Tom , 5 Tom , 3 我怎样才能把它送到- Tom , 10 , 5 , 3 我的测验代码: import time print ('Wha
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()
这在某种程度上是人们经常犯的标准错误。你的代码的最后一部分需要被替换,好吧,不要把代码往下放,而是把代码行放在一边,例如这里和我的项目中的示例
enter code here
if usersClass == "1":
with open("class1.txt","a+") as f:
f.write("{}:Scored {} in {} seconds".format(username,correctAnswers,timeTaken))
因此,您要做的是重新定向/转换它,使其适合并排排列,在这样做时包括逗号。因为这几乎肯定是关于您的,请务必阅读。好的,谢谢,问题是在线上关于该主题的信息非常少,如果你能给我指引正确的方向,我将不胜感激。@chessplayer101我觉得很难相信,因为在过去几个月里,这个问题以各种形式被问了很多次,就这么一个人。@Jornsharpe太好了,你有没有可能把我和一个联系起来,因为我似乎找不到:)没有!我们不是来帮你作弊的。如果你坚持这样做,至少你自己去做。