Advertisement
Guest User

Untitled

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