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))
I want the program to output the results to a text file which works. And then I want it to sort it highest to lowest by score. It kind of works, basically if you score 10/10 in the quiz, in the text file it puts 10 at the bottom but apart from that it sorts it perfectly but how would I fix this issue.
thanks in advance :)