Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time #time.sleep()
- import sys #sys.exit()
- import os #os.path.isfile()
- import json #json.load() , json.dump()
- quizzes = ["Maths",", Business"] #names of the quizzes
- if not os.path.isfile("users.txt"): #checks for the file "users.txt"
- userfile = open("users.txt","w") #if it doesn't exist, it is created
- userfile.close()
- if not os.path.isfile("teacher_password.txt"):
- with open("teacher_password.txt","w") as teacherfile:
- teacherfile.write("admin456") #password for the teacher account is written to file
- if not os.path.isfile("quizzes.txt"):
- with open("quizzes.txt","w") as quizfile:
- for x in quizzes: #each variable in quizzes is stored in a temporary variable: x
- quizfile.write(x) #and then written to the file
- def start():
- userInput = input("Do you have an account? Y or N: ")
- while userInput.lower() not in ("y","n"): #userInput.lower() converts the variable to lower case letters
- userInput = input("Please enter Y or N: ") #this loop will not be broken until the user enters a valid input
- if userInput.lower() == "y":
- login()
- else:
- register()
- def register():
- name = input("Please enter your name: ")
- age = input("Please enter your age: ")
- while 1:
- try:
- age = int(age) #converts age to an integer
- break #breaks the loop
- except ValueError: #but if age can't be converted to an integer (e.g. "one")
- age = input("Please enter a vaild number: ") #the user is asked for their age again
- yearGroup = input("Please enter your year group: ")
- 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
- with open("users.txt") as usercheck:
- users = usercheck.read() #users contains the contents of "users.txt"
- incorrectinputs = ["/",":","\"","?","<",">","|","[\]"] #file names cannot contain these characters so they can't be in username
- for x in username: #stores each character in username in a temporary variable - x
- if x in incorrectinputs: #if x is in the list variable "incorrectinputs"
- username = username.strip(x) #it is erased from username
- while username in users: #if the username has been stored in "users.txt" already
- username = username + "1" #"1" is added to the username to ensure it's unique
- with open("users.txt","a") as userfile:
- userfile.write(username + ", ") #the username is added to "users.txt"
- with open(username +"_info.txt","w") as userinfo: #creates a file with the users info
- userinfo.write("username: " + username + "\n")
- userinfo.write("name: " + name + "\n")
- userinfo.write("age: " + str(age) + "\n")
- userinfo.write("year group: " + str(yearGroup) + "\n") #all of the users details are stored in this file
- print("Welcome ", name, ", your username is: ", username)
- password = input("Please create a password: ")
- with open(username + "_password.txt","w") as passwordfile:
- passwordfile.write(password) #writes the user's password to a password file
- print("You will now be prompted to log in...")
- time.sleep(0.5) #creates a half-second pause
- login()
- def login():
- givenUsername = input("Please enter your username: ")
- givenPassword = input("Please enter your password: ")
- if givenUsername.lower() == "teacher": #checks if the user is trying to log in to the teacher account
- with open("teacher_password.txt") as teacherpwfile: #opens the teacher's password file
- teacherpw = teacherpwfile.read() #the password is read from the file
- if givenPassword == teacherpw:
- admin()
- else:
- print("Incorrect password. Please try again.")
- login()
- try:
- with open(givenUsername + "_password.txt") as pwfile: #tries to open the user's password file
- password = pwfile.read() #the password is read from the file
- except IOError: #unless the file doesn't exist which means that the user doesn't exist
- repeat = input("Invalid username. Press T to try again, or to register, press R: ") #gives the user the option to try again or register
- while repeat.lower() not in ("r","t"): #checks if the users input is valid
- repeat = input("Please enter T or R: ")
- if repeat.lower() == "t":
- login()
- else:
- register()
- if givenPassword == password:
- print("Welcome, ", givenUsername)
- username = givenUsername
- if not os.path.isfile(username +"_results.txt"): #checks for the user's results file
- with open(username +"_results.txt", "w") as resultsfile: #if it doesn't exist the file is created
- resultsfile.write("Username: " + username + "\n") #and the user's username is written to the file
- with open("username.json","w") as u:
- json.dump(username, u) #stores the username in a json file
- main_menu()
- else:
- print("Incorrect password. Please try again.")
- login()
- def main_menu():
- with open("username.json") as u:
- username = json.load(u) #loads the username from a json file
- with open(username +"_results.txt") as resultsfile: #opens the user's results file
- check = resultsfile.read() #the contents of the file are stored in "check"
- 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
- print("You have taken every quiz. You will now be logged out.")
- start()
- with open("quizzes.txt") as quizfile:
- quizzes = quizfile.read() #reads the names of all the quizzes from "quizzes.txt"
- subject = input("Please choose a quiz on one of the following - " + quizzes + ": ")
- while subject.lower() not in quizzes.lower(): #checks if the users input is a valid quiz
- subject = input("Please enter one of the following - " + quizzes + ": ")
- difficulty = input("Choose a difficulty, Easy, Medium or Hard: ")
- while difficulty.lower() not in ("easy","medium","hard"): #checks if the user has entered a valid difficulty
- difficulty = input("Please enter Easy, Medium or Hard: ")
- quizname = (subject.lower() + "quiz" + difficulty.lower()) #creates the name of the quiz from the subject and difficulty
- with open("quizname.json", "w") as q:
- json.dump(quizname, q) #the quiz name is stored in a json file
- with open("difficulty.json", "w") as d:
- json.dump(difficulty, d) #the difficulty is stored in a json file
- quiz()
- def quiz():
- with open("username.json") as u:
- username = json.load(u)
- with open("quizname.json") as q:
- quizname = json.load(q) #loads quiz name from a json file
- with open("difficulty.json") as d:
- difficulty = json.load(d) #loads difficulty from a json file
- with open(username +"_results.txt") as resultsfile:
- check = resultsfile.read()
- if quizname in check: #checks if the quiz name is in the user's results file
- print("You have already taken this quiz.") #if it is, it means they have taken this quiz
- main_menu()
- results = open(username + "_results.txt","a")
- results.write("Quiz: " + quizname + "\n") #adds the name of the quiz to the results file
- questions = []
- with open(quizname + ".csv") as questionfile: #opens the question file
- while 1: #creates a never-ending loop
- in_line = questionfile.readline() #stores a line of the question file to the variable "in_line"
- if not in_line: #checks if "in_line" is empty, which would mean that all of the questions have been read from the file
- break
- questions.append(in_line) #appends each line of the question file to the list variable "questions"
- count = 0 #number of answered questions
- score = 0 #number of correctly answered questions
- for line in questions: #each line of the question file is stored in a temporary variable - "line"
- inputs = line.split(",") #"inputs" is a list variable made by separating "line" into different values by a comma
- question = inputs[0] #the first value in any of the files is always the question
- a = inputs[1] #the second value is always "a"
- b = inputs[2] #the third value is always "b"
- if "correct" in a: #checks for the word "correct" in "a"
- a = a.replace("correct","") #if it's there, it's erased from "a"
- answer = "a" #the correct input becomes the letter "a"
- correctanswer = a #and the correct answer is "a"
- else:
- b = b.replace("correct","") #the same is done for "b"
- answer = "b"
- correctanswer = b
- if difficulty.lower() == "easy": #checks if the difficulty is easy
- question += (" Is it A: " + a + " or B: " + b) #if it is then there are only two options: A or B
- validinputs = ["a","b"]
- invalidinput = ("Please enter A or B.") #this message is outputted when the user's input is invalid
- try:
- c = inputs[3] #checks the question file for a fourth value: "c"
- if "correct" in c:
- c = c.replace("correct","")
- answer = "c"
- correctanswer = c
- if difficulty.lower() == "medium":
- question += " Is it A: " + a + ", B: " + b + " or C: " + c #if the difficulty is medium there are three options: A, B or C
- validinputs = ["a","b","c"]
- invalidinput = ("Please enter A, B or C.")
- except IndexError: #if "c" doesn't exist
- pass #nothing happens
- try:
- d = inputs[4] #checks for a fifth value: "d"
- if "correct" in d:
- d = d.replace("correct","")
- answer = "d"
- correctanswer = d
- if difficulty.lower() == "hard":
- question += " Is it A: " + a + ", B: " + b + ", C: " + c + " or D: " + d #there are four options for hard: A,B,C and D
- validinputs = ["a","b","c","d"]
- invalidinput = ("Please enter A, B, C or D.")
- except IndexError:
- pass
- userAnswer = input(question) #asks the user for their answer
- while userAnswer.lower() not in validinputs: #checks if the user's input is valid
- print(invalidinput)
- userAnswer = input(question)
- if userAnswer.lower() == answer:
- print("Correct!")
- results.write("Question: " + question + "Answer: " + userAnswer + " - Correct\n") #writes the question, answer and result to the user's results file
- score += 1 #adds one to the user's score
- else:
- print("Sorry, the answer was: ", correctanswer) #shows the user the correct answer if they got it wrong
- results.write("Question: " + question + "Answer: " + userAnswer + " - Incorrect\n")
- count += 1 #adds 1 to the # of questions answered
- print("Your final score is: ", score) #outputs final score
- percentage = (score / count) * 100 #calculates percentage from the score and total number of questions
- if not os.path.isfile(quizname + ".json"): #checks for a json file containing the variables "totalscore" and "scorecount"
- scores = open(quizname + ".json","w")#if it doesn't exist, the file is created
- scores.close()
- totalscore = 0
- scorecount = 0 #and both of the variables are set at 0
- else: #if it does exist:
- with open(quizname + ".json") as t:
- totalscore = json.load(t)
- with open(quizname + ".json") as s:
- json.load(s) #both variables are loaded from the file
- totalscore += score #the users score is added to the total number of scores
- scorecount += 1 #the number of times the quiz has been taken increases by 1
- with open(quizname + ".json","w") as s:
- json.dump(scorecount, s)
- with open(quizname + ".json","w") as t:
- json.dump(totalscore, t) #the variables are saved to the json file
- avgscore = totalscore / scorecount #the average score is calculated using "totalscore" and "scorecount"
- print("Your percentage is: ", percentage, "%") #outputs percentage
- if percentage == 0:
- grade = "E" #1 question is worth 20%
- elif percentage == 20:
- grade = "D" #every correct question moves you up a grade
- elif percentage == 40:
- grade = "C"
- elif percentage == 60:
- grade = "B"
- elif percentage == 80:
- grade = "A"
- else:
- grade = "A*" #100% is an A*
- print("Your grade is: ", grade) #outputs grade
- try:
- quizresults = open(quizname + "_results.txt","a") #tries to open the results file for the quiz
- except IOError: #unless it doesn't exist
- quizresults = open(quizname + "_results.txt","w") #in which case it's created
- quizresults.write(username + ": " + str(score) + "\n") #the username and score is written to this file
- quizresults.close()
- results.write("\nFinal score: " + str(score) + "\n") #the user's final score is written to their results file
- results.write("Grade: " + grade + "\n********************\n") #along with their grade
- results.close()
- with open(quizname + "_avgscore.txt","w") as average:
- average.write(str(avgscore)) #the average score for the quiz is saved to another text file
- menu()
- def menu():
- with open("username.json") as u:
- username = json.load(u)
- with open(username + "_results.txt") as check: #opens the user's results file
- resultscheck = check.read() #the contents of the file are stored in "resultscheck"
- if resultscheck.count("Quiz") == 6:
- print("You have taken every quiz. You will now be logged out.")
- start()
- print("""
- If you would like to do another quiz, press C.
- If you would like to log out, press E.
- If you would like to quit, press Q.""")
- userInput = input("Please choose one of the above options to continue: ")
- while userInput.lower() not in ["c","e","q"]: #checks if the user's input is valid
- userInput = input("Please enter C, E or Q: ")
- if userInput.lower() == "q":
- sys.exit() #exits the program
- elif userInput.lower() == "e":
- start()
- else:
- main_menu()
- def admin():
- print("""
- If you would like to check a student's results, press S.
- If you would like to check the results for a quiz, press R.
- If you would like to log out, press E.
- If you would like to quit, press Q""")
- choice = input("Please choose one of the above options to continue: ")
- while choice.lower() not in ["s","r","e","q"]: #checks if the user's input is valid
- choice = input("Please enter S, R, E or Q: ")
- if choice.lower() == "s":
- user_report()
- elif choice.lower() == "r":
- quiz_report()
- elif choice.lower() == "e":
- start()
- else:
- sys.exit()
- def user_report():
- with open("users.txt") as userfile:
- users = userfile.readline() #the contents of "users.txt" is stored in users
- user = input("Please enter their username: ")
- while user not in users: #if user is not in users then the user doesn't exist
- user = input("The username you entered does not exist. Please try again: ")
- try:
- with open(user + "_results.txt") as report: #tries to open the file containing the user's results
- results = report.read() #the contents of the file are stored in "results"
- print(results) #outputs the users results
- except IOError: #unless the file doesn't exist
- print("This user has not completed any quizzes.")
- admin()
- def quiz_report():
- with open("quizzes.txt") as quizfile: #"quizzes.txt" contains the name of every quiz
- quizzes = quizfile.read()
- subject = input("Please enter one of the following - " + quizzes + ":")
- while subject.lower() not in quizzes.lower():
- quizname = input("Please enter one of the following - " + quizzes + ":")
- difficulty = input("Choose a difficulty, Easy, Medium or Hard: ")
- while difficulty.lower() not in ("easy","medium","hard"):
- difficulty = input("Please enter Easy, Medium or Hard.")
- chosenquiz = (subject.lower() + "quiz" + difficulty.lower()) #creates the quizname from the subject and difficulty
- try:
- quizresults = open(chosenquiz + "_results.txt") #tries to open the results file for the chosen quiz
- average = open(chosenquiz + "_avgscore.txt") #as well as the file containing the average score
- except IOError: #unless these files do not exist
- print("No one has taken this quiz yet.")
- admin()
- avgscore = average.read() #the average score is read from the file
- average.close()
- print("Average Score: " + avgscore)
- student_list = []
- score_list = []
- for line in quizresults: #stores each line in quizresults in the temporary variable "line"
- lines = line.split(": ") #creates the list variable "lines" from "line" with the values being separated by a colon
- student = lines[0] #the username is behind the colon so its stored in the variable "student"
- score = int(lines[1]) #the score is in front of the colon so its converted to an integer and stored in the variable "score"
- student_list.append(student) #"student" is added to the list variable "student_list"
- score_list.append(score) #likewise for "score" and "score_list"
- quizresults.close()
- top_score = max(score_list) #takes the highest score from the list
- top_student = student_list[score_list.index(top_score)] #and the username of the corresponding student
- print(top_student + " achieved " + str(top_score) + ", the highest score.")
- with open(top_student + "_info.txt") as details:
- userinfo = details.read() #reads the students details from their info file
- print("The details of this user are:" + userinfo) #outputs the user's details
- admin()
- start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement