Advertisement
fnogal

math_quiz_v3

Jan 10th, 2020
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. # -------------------------------------------------------------------
  2. # Programming 103: Saving and Structuring Data Raspberry Pi Foundation
  3. # Section 1.6
  4. # Math game
  5. # -------------------------------------------------------------------
  6.  
  7. # Collect all questions in a list.
  8. # In this way the list can be changed without impacting the rest of the program
  9. # A better way would be to get the questions and answers from external files
  10. questions = [
  11. "What is the product of 2x2x2",
  12. "What is the value of 2^2^2 (where ^ is the exponentiation operator)",
  13. "What is the square root of 144",
  14. "What is the sum of the first 500 natural numbers (use Gauss' method)"
  15. ]
  16. #
  17. # Collect all answers in a list
  18. answers = [
  19. 8,
  20. 16,
  21. 12,
  22. 125250
  23. ]
  24.  
  25. print("Welcome to the Maths Quiz\n")
  26.  
  27. # initialize variables
  28. highscoreFile = "math_quiz_highscore.txt"
  29.  
  30. # Try to get the previous highscore from file
  31. try:
  32. with open(highscoreFile, "r") as f:
  33. highscore = f.read()
  34. highscore = int(highscore)
  35. except FileNotFoundError:
  36. print("Creating a new " + highscoreFile + " file")
  37. f = open(highscoreFile, "w")
  38. f.write("0")
  39. f.close()
  40. highscore = 0
  41.  
  42. with open(highscoreFile, "r") as f:
  43. highscore = f.read()
  44. highscore = int(highscore)
  45. f.close()
  46.  
  47. score = 0 # The current score for this run of the game
  48. nquestions = len(questions) # Number of questions in the list
  49.  
  50. print("Your previous highest score was " + str(highscore))
  51. print("Can you answer",nquestions,"questions and improve your score?")
  52.  
  53. # Now loop through all the questions
  54. for q in range(nquestions): # The q is used as the index of the questions and answers lists
  55. print("Question " + str(q+1) + ": " + questions[q] + "?")
  56. answer = int(input("Your answer is:>> "))
  57. if answer == answers[q]:
  58. print("Correct")
  59. score = score + 1
  60. else:
  61. print("Incorrect, the answer is: ",answers[q])
  62. print("Your score is ", score)
  63.  
  64.  
  65. if score >= highscore: # if the score of this run is higher than the saved score it replaces it
  66. highscore = score
  67. with open(highscoreFile, "w") as f:
  68. f.write(str(highscore))
  69. f.close()
  70. else:
  71. print("Better luck next time")
  72.  
  73. print("Your highest score is " + str(highscore))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement