Python代码:
#Maths Quiz
#Generate a random number so that your questions are not always the same
#Generate a number and store number
import random #Allows the user to use random selection
import sys #Allows the program to end when finished
def begin():
print("Hello there! Welcome to the Maths Quiz!")
menu()
def quiz():
cor=0 #Correct counter
n=1 #Counter for question number
for i in range(0,10): #i is the counter, the range of 0-10 gives 10 questions
num1 = random.randint(5,10) #First number is a random integer between 5 and 10
num2 = random.randint(1,5) #The second number is a random integer between 1 and 5
operator = random.randint(1,4) #The operator is a random number, 1-4 – this is then decided using an if statement
if operator == 1:
total=num1+num2
answer=int(input("What is {0} + {1}? ".format(num1,num2)))
n=n+1
elif operator == 2:
total=num1-num2
print("Question",n,":")
answer=int(input("What is {0} - {1}? ".format(num1,num2)))
n=n+1
elif operator == 3:
total=num1//num2
#// is used so that the audience of this program can use and understand it
print("Question",n,":")
answer=int(input("What is {0} ÷ {1} to the nearest whole number (no remainder) ".format(num1,num2)))
n=n+1
elif operator == 4:
total=num1*num2
print("Question",n,":")
answer=int(input("What is {0} x {1}? ".format(num1,num2)))
n=n+1
else:
print("Unable to do this.")
if answer==total:
cor=cor+1
print("Correct \n")
else:
print("Incorrect \n")
print("You scored {0} out of 10".format(cor)) #Prints a total score after the quiz
percentage = cor*10 #Calculates a percentage
print("...That is",percentage,"%") #Prints the percentage
print("Adding to scores list!")
addScore(percentage)
def addScore(percentage):
name=input("Enter your name: ")
f=open("scores.txt")
f.write(name+"\n")
f.write(str(percentage)+"%\n")
f.close()
main_menu()
if percentage <= 30: #A statement to decide how well the student has done
print("You should practice more")
elif percentage <= 60:
print("You have a good understanding")
elif percentage <= 80:
print("You have a very good understanding")
elif percentage > 81:
print("You have an excellent understanding! Well done!")
menu()
def viewScores():
f=open("scores.txt","2")
print(" HIGH SCORES ")
print("===========================================")
lines=f.readlines()
for line in lines:
print(line)
print("===========================================")
f.close()
menu()
def menu():
print("===========================================")
print(" What do you want to do? ")
print("===========================================")
print(" 1. QUIZ")
print(" 2. VIEW SCORES")
print(" 3. EXIT")
print("===========================================")
opt = int(input())
if opt == 1:
quiz()
elif opt == 2:
viewScores()
elif opt == 3:
print("Goodbye!")
sys.exit()
begin()
使用#列出评论 目前,我仍然习惯使用写入文件技术并使用一些示例代码中的方法。虽然发生了这些错误,但我在逻辑上使用了示例中的代码,如果可以纠正并解释它们,我会非常感激。
谢谢: - )