Guest User

Untitled

a guest
Mar 26th, 2018
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.95 KB | None | 0 0
  1. import json #json.load(), json.dump()
  2. import time #time.sleep()
  3. import csv #csv.reader(), csv.writer()
  4. import sys #sys.exit()
  5. import os #os.path.isfile()
  6. import configparser #configparser.ConfigParser()
  7. import string #string.ascii_letters
  8.  
  9.  
  10. def start():
  11. user_input = input_checker("""1: Login
  12. 2: Register
  13. Please choose one of the above options: """,(1,2))
  14.  
  15. option_selector((login,register),(1,2),user_input)()
  16.  
  17. def input_checker(question, valid_inputs):
  18. user_input = input(question)
  19.  
  20. while 1:
  21. while [i for i in valid_inputs if type(i) == int]:
  22. try:
  23. user_input = int(user_input)
  24. break
  25. except ValueError:
  26. user_input = input("Please enter a valid number: ")
  27. try:
  28. if not [x for x in user_input if x not in valid_inputs]:
  29. break
  30. user_input = input("Please enter a valid input: ")
  31. except TypeError:
  32. if user_input in valid_inputs:
  33. break
  34. user_input = input("Please enter a valid input: ")
  35.  
  36. return user_input
  37.  
  38. def option_selector(options,numbers,user_input):
  39. option_dict = dict(zip(numbers, options))
  40. return option_dict[user_input]
  41.  
  42. def register():
  43. name = input_checker("Please enter your name: ",tuple(string.ascii_letters)).title()
  44.  
  45. age = input_checker("Please enter your age (you must be 11-18 years old): ",tuple(range(11,19)))
  46.  
  47. year_group = input_checker("Please enter your year group (7-13): ",tuple(range(7,14)))
  48.  
  49. username = name[:3] + str(age)
  50.  
  51. with open("users.csv") as u:
  52. users = u.read()
  53. while username in users:
  54. username += "1"
  55.  
  56. print("Welcome {}, your username is: {}".format(name,username))
  57.  
  58. password = input("Please create a password: ")
  59.  
  60. user_details = (name,age,year_group,username,password)
  61.  
  62. with open("users.csv","a") as u:
  63. writer = csv.writer(u)
  64. writer.writerow(user_details)
  65.  
  66. print("You will now be prompted to login.")
  67.  
  68. time.sleep(0.5)
  69.  
  70. login()
  71.  
  72. def login():
  73. given_username = input("Please enter your username: ").title()
  74.  
  75. given_password = input("Please enter your password: ")
  76.  
  77. config.read("config.ini")
  78.  
  79. admin_password = config["quiz_settings"]["admin_password"]
  80.  
  81. if given_username == "Teacher":
  82. if given_password == admin_password:
  83. admin()
  84. else:
  85. print("Incorrect password.")
  86. login()
  87.  
  88. with open("users.csv") as user_file:
  89. reader = csv.reader(user_file)
  90. user_check = tuple(filter(lambda x: x and given_username == x[3],[row for row in reader]))
  91.  
  92. if not user_check:
  93. user_input = input_checker("""The username you entered doesn't exist.
  94. 1: Try again
  95. 2: Register
  96. Please choose one of the above options to continue: """,[1,2])
  97. option_selector((login,register),(1,2),user_input)()
  98.  
  99. else:
  100. user_details = user_check[0]
  101. password = user_details[4]
  102.  
  103. if given_password == password:
  104. print("Welcome, " + given_username)
  105.  
  106. with open("username.json","w") as u:
  107. json.dump(given_username, u)
  108.  
  109. menu()
  110.  
  111. else:
  112. print("Incorrect password.")
  113. login()
  114.  
  115. def menu():
  116. with open("username.json") as u:
  117. username = json.load(u)
  118.  
  119. subject,subjects,chosen_difficulty,difficulties = quiz_selector()
  120.  
  121. with open("user_results.csv") as u:
  122. reader = csv.reader(u)
  123. user_check = [row for row in reader if row and row[0] == username]
  124.  
  125. if len(user_check) == len(subjects) * len(difficulties):
  126. print("You have taken every quiz. You will now be logged out.")
  127. time.sleep(1)
  128. start()
  129.  
  130. for result in user_check:
  131. if [subject,chosen_difficulty] == result[1:3]:
  132. print("You have already taken this quiz.")
  133. time.sleep(0.5)
  134. menu()
  135.  
  136. quiz_file = subject.lower() + ".csv"
  137.  
  138. score = quiz(quiz_file, chosen_difficulty)
  139.  
  140. percentage = int(round((score/5) * 100))
  141.  
  142. percentage_map = {0: 'E', 20: 'D', 40: 'C', 60: 'B', 80: 'A', 100: 'A*'}
  143.  
  144. grade = percentage_map[percentage]
  145.  
  146. print("""Your final score is: {}/5.
  147. Your percentage is: {}%.
  148. Your grade is: {}.""".format(str(score),str(percentage),grade))
  149.  
  150. user_result = (username,subject,chosen_difficulty,str(score),grade)
  151.  
  152. with open("user_results.csv","a") as u:
  153. writer = csv.writer(u)
  154. writer.writerow(user_result)
  155.  
  156. user_input = input_checker("""1: Take another quiz
  157. 2: Logout
  158. Please choose one of the above options to continue: """,(1,2))
  159.  
  160. option_selector((menu,start),(1,2),user_input)()
  161.  
  162. def quiz_selector():
  163. config.read("config.ini")
  164.  
  165. subjects = tuple(config["quiz_settings"]["subjects"].split(","))
  166.  
  167. subject_index = []
  168.  
  169. for i, topic in enumerate(subjects, start=1):
  170. print((i),": " + topic)
  171. subject_index.append(i)
  172.  
  173. chosen_subject = input_checker("Please choose one of the above subjects: ",subject_index)
  174.  
  175. subject = subjects[(subject_index.index(chosen_subject))]
  176.  
  177. difficulty = input_checker("""1: Easy
  178. 2: Medium
  179. 3: Hard
  180. Please choose one of the above difficulties: """,(1,2,3))
  181.  
  182. difficulties = ("easy","medium","hard")
  183.  
  184. chosen_difficulty = difficulties[difficulty - 1]
  185.  
  186. return subject,subjects,chosen_difficulty,difficulties
  187.  
  188. def quiz(quiz_file,difficulty):
  189. with open(quiz_file) as q:
  190. reader = csv.reader(q)
  191. questions = [line for line in reader]
  192.  
  193. difficulty_map = {"easy" : (0,5),
  194. "medium" : (5,10),
  195. "hard" : (10,15)}
  196.  
  197. question_reader = difficulty_map[difficulty]
  198.  
  199. quiz_questions = questions[(question_reader[0]):(question_reader[1])]
  200.  
  201. score = 0
  202.  
  203. for line in quiz_questions:
  204. x, question = line[0:2]
  205.  
  206. answers = tuple(filter(lambda a: a != x and a != question, line))
  207.  
  208. valid_answers = []
  209.  
  210. print(question)
  211.  
  212. for i, answer in enumerate(answers,start=1):
  213. print((i),": " + answer)
  214. valid_answers.append(i)
  215.  
  216. user_answer = input_checker("Please choose one of the above answers: ",valid_answers)
  217.  
  218. correct_answer = line[int(x)]
  219.  
  220. correct_input = valid_answers[answers.index(correct_answer)]
  221.  
  222. if user_answer == correct_input:
  223. print("Correct!")
  224. score += 1
  225.  
  226. else:
  227. print("Sorry, the correct answer was: {}".format(str(correct_answer)))
  228.  
  229. return score
  230.  
  231. def admin():
  232. user_input = input_checker("""1: Check a user's results
  233. 2: Check the results for a quiz
  234. 3: Logout
  235. Please choose one of the above options to continue: """,(1,2,3))
  236.  
  237. option_selector((user_report,quiz_report,start),(1,2,3),user_input)()
  238.  
  239. def user_report():
  240. username = input("Please enter their username: ").title()
  241.  
  242. with open("user_results.csv") as u:
  243. reader = csv.reader(u)
  244. user_result = [row for row in reader if row and username == row[0]]
  245.  
  246. if not user_result:
  247. print("This user hasn't completed any quizzes.")
  248. admin()
  249.  
  250. for result in user_result:
  251. print("""Subject: {}
  252. Difficulty: {}
  253. Score: {}
  254. Grade: {}\n""".format(result[1],result[2].title(),result[3],result[4]))
  255.  
  256. admin()
  257.  
  258. def quiz_report():
  259. subject,subjects,difficulty,difficulties = quiz_selector()
  260.  
  261. with open("user_results.csv") as u:
  262. reader = csv.reader(u)
  263. user_result = [row for row in reader if row and [subject,difficulty] == row[1:3]]
  264.  
  265. if not user_result:
  266. print("No-one has taken this quiz.")
  267. admin()
  268.  
  269. total_score = 0
  270.  
  271. for result in user_result:
  272. total_score += int(result[3])
  273.  
  274. avg_score = round(total_score/len(user_result),1)
  275.  
  276. print("The average score for this quiz is {}.".format(str(avg_score)))
  277.  
  278. scores = sorted(user_result,key=lambda score: int(score[3]),reverse=True)
  279.  
  280. highest_user = scores[0]
  281.  
  282. with open("users.csv") as u:
  283. with open("users.csv") as user_file:
  284. reader = csv.reader(user_file)
  285. user = tuple(filter(lambda x: x and highest_user[0] == x[3],[line for line in reader]))
  286.  
  287. user_details = user[0]
  288.  
  289. print("""The highest score was {}, achieved by {}. The details of this user are:
  290. Name: {}
  291. Age: {}
  292. Year Group: {}""".format(highest_user[3],highest_user[0],user_details[0],user_details[1],user_details[2]))
  293.  
  294. admin()
  295.  
  296. config = configparser.ConfigParser()
  297.  
  298. for x in ("users.csv","user_results.csv"):
  299. if not os.path.isfile(x):
  300. open(x,"w").close()
  301.  
  302. if not os.path.isfile("config.ini"):
  303. config["quiz_settings"] = {"subjects": "Maths,Business","admin_password": "admin456"}
  304. with open("config.ini","w") as config_file:
  305. config.write(config_file)
  306.  
  307. start()
Add Comment
Please, Sign In to add comment