import random #This will import the random function, allowing me to ask the user random questions
import sys #This will allow me to exit the program within the program
score = 0
print ("What is your name?")
name = input()
if name=="" or name==" " or name.isdigit():
print("Error")
sys.exit()
print("Hello",name,", are you in class 1,2 or 3?")
print("\nEnter '1' for class 1, enter '2' for class 2 and enter '3' for class 3")
class_name = (input())
if class_name=="" or class_name==" ":
print("Error")
sys.exit()
print ('\nYou will be asked 10 questions involving addition, subtraction and multiplicaton')
for x in range(10):#Loop will reapeat 10 times
operation2 = ['+','-','*']#These are the operations I will use
operation = random.choice(operation2)#Randomising the operation that will be used
num1=random.randint(1,10)#Random number 1-10
num2=random.randint(1,10)#Random number 1-10
num3=int(eval(str(num1) + operation + str(num2)))
print ("\n",num1,operation,num2)#Prints the question
answer=int(input())#User input
if answer=="" or answer==" ":
print("Error")
sys.exit()
if answer == num3:
print ("Correct")
score += 1#Adds 1 to 'score'
else:
print("Incorrect")
print("\nYou scored",score,"out of 10") #This will display your final score out of 10
if class_name== '1':
with open("Class 1 Highest Score.txt", "r") as f:
lines = f.readlines()
lines.append("{}:{}\n".format(score,name))
lines.sort(reverse=True)
with open("Class 1 Highest Score.txt", "w") as f:
f.write("".join(lines))
if class_name== '2':
with open("Class 2 Highest Score.txt", "r") as f:
lines = f.readlines()
lines.append("{}:{}\n".format(score,name))
lines.sort(reverse=True)
with open("Class 2 Highest Score.txt", "w") as f:
f.write("".join(lines))
if class_name== '3':
with open("Class 3 Highest Score.txt", "r") as f:
lines = f.readlines()
lines.append("{}:{}\n".format(score,name))
lines.sort(reverse=True)
with open("Class 3 Highest Score.txt", "w") as f:
f.write("".join(lines))
我希望程序将结果输出到有效的文本文件中。然后我希望它按分数从最高到最低排序。它有点工作,基本上如果你在测验中得分10/10,在文本文件中它将10放在底部但除此之外它对它进行了完美排序,但我将如何解决这个问题。
提前感谢:)