我对python相当陌生,我需要做一个程序来问10个问题,将分数保存到一个文件中,并允许有人从文件中读取分数。你知道吗
我的问题是:我需要检查做过测试的人是否在文件中有记录,如果有,我需要把他们的分数加到记录的末尾。你知道吗
记录应如下所示:
名字,分数,分数,分数,分数, 等等,这样就可以用逗号将它们分开。你知道吗
我也在寻找最简单的答案,而不是最有效的。另外,如果您可以对代码进行注释,这将使它变得更容易。以下是我目前的代码:
import random
import math
import operator as op
import sys
import re
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, num1)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correct_result = operation(num1, num2)
print ("What is {} {} {}?".format(num1, rand_key, num2))
while True:
try:
user_answer = int(input("Your answer: "))
except ValueError:
print("Only enter numbers!")
continue
else:
break
if user_answer != correct_result:
print ("Incorrect. The right answer is {}".format(correct_result))
return False
else:
print("Correct!")
return True
print("1. Are you a student?")
print("2. Are you a teacher?")
print("3. Exit")
while True:
try:
status = int(input("Please select an option:"))
except ValueError:
print("Please enter a number!")
else:
if status not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
break
if status == 1:
username=input("What is your name?")
while not re.match("^[A-Za-z ]*$", username) or username=="":
username=input(str("Please enter a valid name (it must not contain numbers or symbols)."))
print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))
while True:
try:
users_class = int(input("Which class are you in? (1,2 or 3)"))
except ValueError:
print("Please enter a number!")
else:
if users_class not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
break
correct_answers = 0
num_questions = 10
for i in range(num_questions):
if test():
correct_answers +=1
print("{}: You got {}/{} {} correct.".format(username, correct_answers, num_questions,
'question' if (correct_answers==1) else 'questions'))
if users_class == 1:
class1 = open("Class1.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class1.write(newRecord)
class1.close()
elif users_class == 2:
class2 = open("Class2.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class2.write(newRecord)
class2.close()
elif users_class == 3:
class3 = open("Class3.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class3.write(newRecord)
class3.close()
else:
print("Sorry, we can not save your data as the class you entered is not valid.")
首先,定义这些功能:
现在,在代码的最后一部分(实际上是写分数的地方)变得简单多了。下面是一个写分数的例子:
Class1.txt中将有两行: 菲尔,7,6,9 爱丽丝,6岁
我们将整个文件读入一个dict(实际上是一个defaultdict(list)), 通过使用defaultdict(list),我们不必担心更新和添加记录之间的区别。你知道吗
还要注意的是,我们不需要单独的if/elif案例来读/写文件。
"Scores%d.txt"%users_class
提供文件名。你知道吗编辑:
在“test”函数之前添加此函数:
在此之后,如果有“if users\u class==1:”,请执行以下操作:
对另外两个if也一样。你知道吗
让我知道你的想法!你知道吗
尝试使用字典保存现有文件数据。你知道吗
例如,读取名为“str”的变量中的文件。然后这样做:
当你有一个新的分数时,你应该做:
并将数据保存回文件:
并将“output”的内容保存到文件中。你知道吗
PS:如果您不受文件格式的约束,那么可以使用JSON文件。如果你愿意,我可以告诉你更多。你知道吗
希望有帮助, 亚历克斯
相关问题 更多 >
编程相关推荐