Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -------------------------------------------------------------------
- # Programming 103: Saving and Structuring Data Raspberry Pi Foundation
- # Section 1.6
- # Math game
- # -------------------------------------------------------------------
- # Collect all questions in a list.
- # In this way the list can be changed without impacting the rest of the program
- # A better way would be to get the questions and answers from external files
- questions = [
- "What is the product of 2x2x2",
- "What is the value of 2^2^2 (where ^ is the exponentiation operator)",
- "What is the square root of 144",
- "What is the sum of the first 500 natural numbers (use Gauss' method)"
- ]
- #
- # Collect all answers in a list
- answers = [
- 8,
- 16,
- 12,
- 125250
- ]
- print("Welcome to the Maths Quiz\n")
- # initialize variables
- highscoreFile = "math_quiz_highscore.txt"
- # Try to get the previous highscore from file
- try:
- with open(highscoreFile, "r") as f:
- highscore = f.read()
- highscore = int(highscore)
- except FileNotFoundError:
- print("Creating a new " + highscoreFile + " file")
- f = open(highscoreFile, "w")
- f.write("0")
- f.close()
- highscore = 0
- with open(highscoreFile, "r") as f:
- highscore = f.read()
- highscore = int(highscore)
- f.close()
- score = 0 # The current score for this run of the game
- nquestions = len(questions) # Number of questions in the list
- print("Your previous highest score was " + str(highscore))
- print("Can you answer",nquestions,"questions and improve your score?")
- # Now loop through all the questions
- for q in range(nquestions): # The q is used as the index of the questions and answers lists
- print("Question " + str(q+1) + ": " + questions[q] + "?")
- answer = int(input("Your answer is:>> "))
- if answer == answers[q]:
- print("Correct")
- score = score + 1
- else:
- print("Incorrect, the answer is: ",answers[q])
- print("Your score is ", score)
- if score >= highscore: # if the score of this run is higher than the saved score it replaces it
- highscore = score
- with open(highscoreFile, "w") as f:
- f.write(str(highscore))
- f.close()
- else:
- print("Better luck next time")
- print("Your highest score is " + str(highscore))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement