Advertisement
Guest User

Untitled

a guest
Dec 3rd, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.23 KB | None | 0 0
  1. Fergus is creating python login and quiz by David Mesicsky
  2.  
  3. import time
  4.  
  5. import sys # no need for separate lines per import
  6.  
  7. import os
  8.  
  9. import json
  10. # two lines to separate imports and code
  11. quizzes = ["Maths",", Business"] # consider tuples
  12.  
  13. if not os.path.isfile("users.txt"):
  14. userfile = open("users.txt","w")
  15.  
  16. userfile.close()
  17.  
  18. if not os.path.isfile("teacher_password.txt"):
  19. # just open the file instead of checking whether it exists
  20. with open("teacher_password.txt","w") as teacherfile:
  21. teacherfile.write("admin456")
  22.  
  23. if not os.path.isfile("quizzes.txt"):
  24. with open("quizzes.txt","w") as quizfile:
  25. for x in quizzes:
  26. quizfile.write(x)
  27.  
  28.  
  29. def start():
  30. # functions go before top level code
  31. userInput = input("Do you have an account? Y or N: ") #.lower()
  32.  
  33. while userInput.lower() not in ("y","n"):
  34. userInput = input("Please enter Y or N: ")
  35.  
  36. if userInput.lower() == "y":
  37. login()
  38.  
  39. else:
  40. register()
  41.  
  42.  
  43. def register():
  44. name = input("Please enter your name: ")
  45.  
  46. age = input("Please enter your age: ")
  47.  
  48. while 1:
  49.  
  50. try:
  51. age = int(age)
  52. break
  53.  
  54. except ValueError:
  55. age = input("Please enter a vaild number: ")
  56. # what if the user enters incorrect age again?
  57.  
  58. yearGroup = input("Please enter your year group: ")
  59.  
  60. username = name[:3] + str(age)
  61.  
  62. with open("users.txt") as usercheck:
  63. users = usercheck.read()
  64.  
  65. incorrectinputs = ["/",":","\"","?","<",">","|","[\]"]
  66. # just do '"'
  67. for x in username:
  68. if x in incorrectinputs:
  69. username = username.strip(x)
  70.  
  71. while username in users:
  72. username = username + "1" # username += '1'
  73.  
  74. with open("users.txt","a") as userfile:
  75. userfile.write(username + ", ")
  76.  
  77. with open(username +"_info.txt","w") as userinfo:
  78. userinfo.write("username: " + username + "\n")
  79.  
  80. userinfo.write("name: " + name + "\n")
  81.  
  82. userinfo.write("age: " + str(age) + "\n")
  83.  
  84. userinfo.write("year group: " + str(yearGroup) + "\n")
  85. # why do str(yearGroup)?
  86.  
  87. print("Welcome ", name, ", your username is: ", username)
  88.  
  89. password = input("Please create a password: ")
  90.  
  91. with open(username + "_password.txt","w") as passwordfile:
  92. passwordfile.write(password)
  93.  
  94. print("You will now be prompted to log in...")
  95.  
  96. time.sleep(0.5)
  97.  
  98. login()
  99.  
  100.  
  101. def login():
  102. givenUsername = input("Please enter your username: ")
  103.  
  104. givenPassword = input("Please enter your password: ")
  105.  
  106. if givenUsername.lower() == "teacher":
  107. # no case-sensitivity?
  108. with open("teacher_password.txt") as teacherpwfile:
  109. # plaintext password?
  110. teacherpw = teacherpwfile.read()
  111.  
  112. if givenPassword == teacherpw:
  113. admin()
  114.  
  115. else:
  116. print("Incorrect password. Please try again.")
  117. login()
  118.  
  119. try:
  120. with open(givenUsername + "_password.txt") as pwfile:
  121. password = pwfile.read()
  122.  
  123. except IOError:
  124. repeat = input("Invalid username. Press T to try again, or to register, press R: ")
  125.  
  126. while repeat.lower() not in ("r","t"):
  127. repeat = input("Please enter T or R: ")
  128.  
  129. if repeat.lower() == "t":
  130. login()
  131.  
  132. else:
  133. register()
  134.  
  135. if givenPassword == password:
  136. print("Welcome, ", givenUsername)
  137.  
  138. username = givenUsername
  139.  
  140. if not os.path.isfile(username +"_results.txt"):
  141. with open(username +"_results.txt", "w") as resultsfile:
  142. resultsfile.write("Username: " + username + "\n")
  143.  
  144. with open("username.json","w") as u:
  145. json.dump(username, u)
  146.  
  147. main_menu()
  148.  
  149. else:
  150. print("Incorrect password. Please try again.")
  151. login()
  152.  
  153.  
  154. def main_menu():
  155. with open("username.json") as u:
  156. username = json.load(u)
  157.  
  158. with open(username + "_results.txt") as resultsfile:
  159. check = resultsfile.read()
  160.  
  161. if check.count("Quiz") == 6:
  162. print("You have taken every quiz. You will now be logged out.")
  163. start()
  164.  
  165. with open("quizzes.txt") as quizfile:
  166. quizzes = quizfile.read()
  167.  
  168. subject = input("Please choose a quiz on one of the following - " + quizzes + ": ")
  169.  
  170. while subject.lower() not in quizzes.lower():
  171. subject = input("Please enter one of the following - " + quizzes + ": ")
  172.  
  173. difficulty = input("Choose a difficulty, Easy, Medium or Hard: ")
  174.  
  175. while difficulty.lower() not in ("easy","medium","hard"):
  176. difficulty = input("Please enter Easy, Medium or Hard: ")
  177.  
  178. quizname = (subject.lower() + "quiz" + difficulty.lower())
  179.  
  180. with open("quizname.json", "w") as q:
  181. json.dump(quizname, q)
  182.  
  183. with open("difficulty.json", "w") as d:
  184. json.dump(difficulty, d)
  185.  
  186. quiz()
  187.  
  188.  
  189. def quiz():
  190. with open("username.json") as u:
  191. username = json.load(u)
  192.  
  193. with open("quizname.json") as q:
  194. quizname = json.load(q)
  195.  
  196. with open("difficulty.json") as d:
  197. difficulty = json.load(d)
  198.  
  199. with open(username +"_results.txt") as resultsfile:
  200. check = resultsfile.read()
  201.  
  202. if quizname in check:
  203. print("You have already taken this quiz.")
  204. main_menu()
  205.  
  206. results = open(username + "_results.txt","a")
  207. results.write("Quiz: " + quizname + "\n")
  208.  
  209. questions = []
  210.  
  211. with open(quizname + ".csv") as questionfile:
  212. while 1:
  213. in_line = questionfile.readline()
  214. # use a for loop e.g
  215. # for line in questionfile:
  216. # ...
  217. if not in_line:
  218. break
  219.  
  220. questions.append(in_line)
  221.  
  222. count = 0
  223.  
  224. score = 0
  225.  
  226. for line in questions:
  227. inputs = line.split(",")
  228.  
  229. question = inputs[0]
  230.  
  231. a = inputs[1]
  232.  
  233. b = inputs[2]
  234.  
  235. # question, a, b = inputs
  236.  
  237. if "correct" in a:
  238. a = a.replace("correct","")
  239.  
  240. answer = "a"
  241.  
  242. correctanswer = a
  243.  
  244. else:
  245. b = b.replace("correct","")
  246.  
  247. answer = "b"
  248.  
  249. correctanswer = b
  250.  
  251. if difficulty.lower() == "easy":
  252. question += (" Is it A: " + a + " or B: " + b)
  253.  
  254. validinputs = ["a","b"]
  255.  
  256. invalidinput = ("Please enter A or B.")
  257.  
  258. try:
  259. c = inputs[3]
  260.  
  261. if "correct" in c:
  262. c = c.replace("correct","")
  263.  
  264. answer = "c"
  265.  
  266. correctanswer = c
  267.  
  268. if difficulty.lower() == "medium":
  269. question += " Is it A: " + a + ", B: " + b + " or C: " + c
  270.  
  271. validinputs = ["a","b","c"]
  272.  
  273. invalidinput = ("Please enter A, B or C.")
  274.  
  275. except IndexError:
  276. pass
  277.  
  278. try:
  279. d = inputs[4]
  280.  
  281. if "correct" in d:
  282.  
  283. d = d.replace("correct","") # use '' for characters and empty
  284. # strings
  285.  
  286. answer = "d"
  287.  
  288. correctanswer = d
  289.  
  290. if difficulty.lower() == "hard":
  291.  
  292. question += " Is it A: " + a + ", B: " + b + ", C: " + c + " or D: " + d
  293. # use % formatting
  294.  
  295. validinputs = ["a","b","c","d"]
  296.  
  297. invalidinput = ("Please enter A, B, C or D.")
  298.  
  299. except IndexError:
  300. pass
  301.  
  302. userAnswer = input(question)
  303.  
  304. while userAnswer.lower() not in validinputs:
  305. print(invalidinput)
  306.  
  307. userAnswer = input(question)
  308.  
  309. if userAnswer.lower() == answer:
  310. print("Correct!")
  311.  
  312. results.write("Question: " + question + "Answer: " + userAnswer + " - Correct\n")
  313.  
  314. score += 1
  315.  
  316. else:
  317. print("Sorry, the answer was: ", correctanswer)
  318.  
  319. results.write("Question: " + question + "Answer: " + userAnswer + " - Incorrect\n")
  320.  
  321. count += 1
  322.  
  323. print("Your final score is: ", score)
  324.  
  325. percentage = (score / count) * 100
  326.  
  327. if not os.path.isfile(quizname + ".json"):
  328. scores = open(quizname + ".json","w")
  329.  
  330. scores.close()
  331.  
  332. totalscore = 0
  333.  
  334. scorecount = 0
  335.  
  336. else:
  337. with open(quizname + ".json") as t:
  338. totalscore = json.load(t)
  339.  
  340. with open(quizname + ".json") as s:
  341. json.load(s)
  342.  
  343. totalscore += score
  344.  
  345. scorecount += 1
  346.  
  347. with open(quizname + ".json","w") as s:
  348. json.dump(scorecount, s)
  349.  
  350. with open(quizname + ".json","w") as t:
  351. json.dump(totalscore, t)
  352.  
  353. avgscore = totalscore / scorecount
  354.  
  355. print("Your percentage is: ", percentage, "%")
  356.  
  357. if percentage == 0:
  358. grade = "E"
  359.  
  360. elif percentage == 20:
  361. grade = "D"
  362.  
  363. elif percentage == 40:
  364. grade = "C"
  365.  
  366. elif percentage == 60:
  367. grade = "B"
  368.  
  369. elif percentage == 80:
  370. grade = "A"
  371.  
  372. else:
  373. grade = "A*"
  374.  
  375. # use a map f.e.
  376. # percentage_map = {
  377. # 0: 'E',
  378. # 20: 'D',
  379. # 40: 'C',
  380. # 60: 'B',
  381. # 80: 'A',
  382. # 100: "A*"
  383. #}
  384. #
  385. # grade = percentage_map[percentage]
  386.  
  387. print("Your grade is: ", grade)
  388.  
  389. try:
  390. quizresults = open(quizname + "_results.txt","a")
  391.  
  392. except IOError:
  393. quizresults = open(quizname + "_results.txt","w")
  394.  
  395. quizresults.write(username + ": " + str(score) + "\n")
  396.  
  397. quizresults.close()
  398.  
  399. results.write("\nFinal score: " + str(score) + "\n")
  400.  
  401. results.write("Grade: " + grade + "\n********************\n")
  402.  
  403. results.close()
  404.  
  405. with open(quizname + "_avgscore.txt","w") as average:
  406. average.write(str(avgscore))
  407.  
  408. menu()
  409.  
  410.  
  411. def menu():
  412. with open("username.json") as u:
  413. username = json.load(u)
  414.  
  415. with open(username + "_results.txt") as check:
  416. resultscheck = check.read()
  417.  
  418. if resultscheck.count("Quiz") == 6:
  419. print("You have taken every quiz. You will now be logged out.")
  420.  
  421. start()
  422.  
  423. print("""
  424. If you would like to do another quiz, press C.
  425. If you would like to log out, press E.
  426. If you would like to quit, press Q.""")
  427.  
  428. userInput = input("Please choose one of the above options to continue: ")
  429.  
  430. while userInput.lower() not in ["c","e","q"]:
  431. userInput = input("Please enter C, E or Q: ")
  432.  
  433. if userInput.lower() == "q":
  434. sys.exit()
  435.  
  436. elif userInput.lower() == "e":
  437. start()
  438.  
  439. else:
  440. main_menu()
  441.  
  442.  
  443. def admin():
  444. print("""
  445. If you would like to check a student's results, press S.
  446. If you would like to check the results for a quiz, press R.
  447. If you would like to log out, press E.
  448. If you would like to quit, press Q""")
  449.  
  450. choice = input("Please choose one of the above options to continue: ")
  451.  
  452. while choice.lower() not in ["s","r","e","q"]:
  453. choice = input("Please enter S, R, E or Q: ")
  454.  
  455. if choice.lower() == "s":
  456. user_report()
  457.  
  458. elif choice.lower() == "r":
  459. quiz_report()
  460.  
  461. elif choice.lower() == "e":
  462. start()
  463.  
  464. else:
  465. sys.exit()
  466.  
  467.  
  468. def user_report():
  469. with open("users.txt") as userfile:
  470. users = userfile.readline()
  471.  
  472. user = input("Please enter their username: ")
  473.  
  474. while user not in users:
  475. user = input("The username you entered does not exist. Please try again: ")
  476.  
  477. try:
  478. with open(user + "_results.txt") as report:
  479. results = report.read()
  480.  
  481. print(results)
  482.  
  483. except IOError:
  484. print("This user has not completed any quizzes.")
  485.  
  486. admin()
  487.  
  488.  
  489. def quiz_report():
  490. with open("quizzes.txt") as quizfile:
  491. quizzes = quizfile.read()
  492.  
  493. subject = input("Please enter one of the following - " + quizzes + ":")
  494.  
  495. while subject.lower() not in quizzes.lower():
  496. quizname = input("Please enter one of the following - " + quizzes + ":")
  497.  
  498. difficulty = input("Choose a difficulty, Easy, Medium or Hard: ")
  499.  
  500. while difficulty.lower() not in ("easy","medium","hard"):
  501. difficulty = input("Please enter Easy, Medium or Hard.")
  502.  
  503. chosenquiz = (subject.lower() + "quiz" + difficulty.lower())
  504.  
  505. try:
  506. quizresults = open(chosenquiz + "_results.txt")
  507.  
  508. average = open(chosenquiz + "_avgscore.txt")
  509.  
  510. except IOError:
  511. print("No one has taken this quiz yet.")
  512.  
  513. admin()
  514.  
  515. avgscore = average.read()
  516.  
  517. average.close()
  518.  
  519. print("Average Score: " + avgscore)
  520.  
  521. student_list = []
  522. score_list = []
  523.  
  524. for line in quizresults:
  525. lines = line.split(": ")
  526.  
  527. student = lines[0]
  528.  
  529. score = int(lines[1])
  530.  
  531. student_list.append(student)
  532.  
  533. score_list.append(score)
  534.  
  535. quizresults.close()
  536.  
  537. top_score = max(score_list)
  538.  
  539. top_student = student_list[score_list.index(top_score)]
  540.  
  541. print(top_student + " achieved " + str(top_score) + ", the highest score.")
  542.  
  543. with open(top_student + "_info.txt") as details:
  544. userinfo = details.read()
  545.  
  546. print("The details of this user are:" + userinfo)
  547.  
  548. admin()
  549.  
  550.  
  551. start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement