Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Fergus is creating python login and quiz by David Mesicsky
- import time
- import sys # no need for separate lines per import
- import os
- import json
- # two lines to separate imports and code
- quizzes = ["Maths",", Business"] # consider tuples
- if not os.path.isfile("users.txt"):
- userfile = open("users.txt","w")
- userfile.close()
- if not os.path.isfile("teacher_password.txt"):
- # just open the file instead of checking whether it exists
- with open("teacher_password.txt","w") as teacherfile:
- teacherfile.write("admin456")
- if not os.path.isfile("quizzes.txt"):
- with open("quizzes.txt","w") as quizfile:
- for x in quizzes:
- quizfile.write(x)
- def start():
- # functions go before top level code
- userInput = input("Do you have an account? Y or N: ") #.lower()
- while userInput.lower() not in ("y","n"):
- userInput = input("Please enter Y or N: ")
- 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)
- break
- except ValueError:
- age = input("Please enter a vaild number: ")
- # what if the user enters incorrect age again?
- yearGroup = input("Please enter your year group: ")
- username = name[:3] + str(age)
- with open("users.txt") as usercheck:
- users = usercheck.read()
- incorrectinputs = ["/",":","\"","?","<",">","|","[\]"]
- # just do '"'
- for x in username:
- if x in incorrectinputs:
- username = username.strip(x)
- while username in users:
- username = username + "1" # username += '1'
- with open("users.txt","a") as userfile:
- userfile.write(username + ", ")
- with open(username +"_info.txt","w") as userinfo:
- userinfo.write("username: " + username + "\n")
- userinfo.write("name: " + name + "\n")
- userinfo.write("age: " + str(age) + "\n")
- userinfo.write("year group: " + str(yearGroup) + "\n")
- # why do str(yearGroup)?
- print("Welcome ", name, ", your username is: ", username)
- password = input("Please create a password: ")
- with open(username + "_password.txt","w") as passwordfile:
- passwordfile.write(password)
- print("You will now be prompted to log in...")
- time.sleep(0.5)
- login()
- def login():
- givenUsername = input("Please enter your username: ")
- givenPassword = input("Please enter your password: ")
- if givenUsername.lower() == "teacher":
- # no case-sensitivity?
- with open("teacher_password.txt") as teacherpwfile:
- # plaintext password?
- teacherpw = teacherpwfile.read()
- if givenPassword == teacherpw:
- admin()
- else:
- print("Incorrect password. Please try again.")
- login()
- try:
- with open(givenUsername + "_password.txt") as pwfile:
- password = pwfile.read()
- except IOError:
- repeat = input("Invalid username. Press T to try again, or to register, press R: ")
- while repeat.lower() not in ("r","t"):
- 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"):
- with open(username +"_results.txt", "w") as resultsfile:
- resultsfile.write("Username: " + username + "\n")
- with open("username.json","w") as u:
- json.dump(username, u)
- main_menu()
- else:
- print("Incorrect password. Please try again.")
- login()
- def main_menu():
- with open("username.json") as u:
- username = json.load(u)
- with open(username + "_results.txt") as resultsfile:
- check = resultsfile.read()
- if check.count("Quiz") == 6:
- print("You have taken every quiz. You will now be logged out.")
- start()
- with open("quizzes.txt") as quizfile:
- quizzes = quizfile.read()
- subject = input("Please choose a quiz on one of the following - " + quizzes + ": ")
- while subject.lower() not in quizzes.lower():
- 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"):
- difficulty = input("Please enter Easy, Medium or Hard: ")
- quizname = (subject.lower() + "quiz" + difficulty.lower())
- with open("quizname.json", "w") as q:
- json.dump(quizname, q)
- with open("difficulty.json", "w") as d:
- json.dump(difficulty, d)
- quiz()
- def quiz():
- with open("username.json") as u:
- username = json.load(u)
- with open("quizname.json") as q:
- quizname = json.load(q)
- with open("difficulty.json") as d:
- difficulty = json.load(d)
- with open(username +"_results.txt") as resultsfile:
- check = resultsfile.read()
- if quizname in check:
- print("You have already taken this quiz.")
- main_menu()
- results = open(username + "_results.txt","a")
- results.write("Quiz: " + quizname + "\n")
- questions = []
- with open(quizname + ".csv") as questionfile:
- while 1:
- in_line = questionfile.readline()
- # use a for loop e.g
- # for line in questionfile:
- # ...
- if not in_line:
- break
- questions.append(in_line)
- count = 0
- score = 0
- for line in questions:
- inputs = line.split(",")
- question = inputs[0]
- a = inputs[1]
- b = inputs[2]
- # question, a, b = inputs
- if "correct" in a:
- a = a.replace("correct","")
- answer = "a"
- correctanswer = a
- else:
- b = b.replace("correct","")
- answer = "b"
- correctanswer = b
- if difficulty.lower() == "easy":
- question += (" Is it A: " + a + " or B: " + b)
- validinputs = ["a","b"]
- invalidinput = ("Please enter A or B.")
- try:
- c = inputs[3]
- 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
- validinputs = ["a","b","c"]
- invalidinput = ("Please enter A, B or C.")
- except IndexError:
- pass
- try:
- d = inputs[4]
- if "correct" in d:
- d = d.replace("correct","") # use '' for characters and empty
- # strings
- answer = "d"
- correctanswer = d
- if difficulty.lower() == "hard":
- question += " Is it A: " + a + ", B: " + b + ", C: " + c + " or D: " + d
- # use % formatting
- validinputs = ["a","b","c","d"]
- invalidinput = ("Please enter A, B, C or D.")
- except IndexError:
- pass
- userAnswer = input(question)
- while userAnswer.lower() not in validinputs:
- print(invalidinput)
- userAnswer = input(question)
- if userAnswer.lower() == answer:
- print("Correct!")
- results.write("Question: " + question + "Answer: " + userAnswer + " - Correct\n")
- score += 1
- else:
- print("Sorry, the answer was: ", correctanswer)
- results.write("Question: " + question + "Answer: " + userAnswer + " - Incorrect\n")
- count += 1
- print("Your final score is: ", score)
- percentage = (score / count) * 100
- if not os.path.isfile(quizname + ".json"):
- scores = open(quizname + ".json","w")
- scores.close()
- totalscore = 0
- scorecount = 0
- else:
- with open(quizname + ".json") as t:
- totalscore = json.load(t)
- with open(quizname + ".json") as s:
- json.load(s)
- totalscore += score
- scorecount += 1
- with open(quizname + ".json","w") as s:
- json.dump(scorecount, s)
- with open(quizname + ".json","w") as t:
- json.dump(totalscore, t)
- avgscore = totalscore / scorecount
- print("Your percentage is: ", percentage, "%")
- if percentage == 0:
- grade = "E"
- elif percentage == 20:
- grade = "D"
- elif percentage == 40:
- grade = "C"
- elif percentage == 60:
- grade = "B"
- elif percentage == 80:
- grade = "A"
- else:
- grade = "A*"
- # use a map f.e.
- # percentage_map = {
- # 0: 'E',
- # 20: 'D',
- # 40: 'C',
- # 60: 'B',
- # 80: 'A',
- # 100: "A*"
- #}
- #
- # grade = percentage_map[percentage]
- print("Your grade is: ", grade)
- try:
- quizresults = open(quizname + "_results.txt","a")
- except IOError:
- quizresults = open(quizname + "_results.txt","w")
- quizresults.write(username + ": " + str(score) + "\n")
- quizresults.close()
- results.write("\nFinal score: " + str(score) + "\n")
- results.write("Grade: " + grade + "\n********************\n")
- results.close()
- with open(quizname + "_avgscore.txt","w") as average:
- average.write(str(avgscore))
- menu()
- def menu():
- with open("username.json") as u:
- username = json.load(u)
- with open(username + "_results.txt") as check:
- resultscheck = check.read()
- 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"]:
- userInput = input("Please enter C, E or Q: ")
- if userInput.lower() == "q":
- sys.exit()
- 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"]:
- 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()
- user = input("Please enter their username: ")
- while user not in users:
- user = input("The username you entered does not exist. Please try again: ")
- try:
- with open(user + "_results.txt") as report:
- results = report.read()
- print(results)
- except IOError:
- print("This user has not completed any quizzes.")
- admin()
- def quiz_report():
- with open("quizzes.txt") as quizfile:
- 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())
- try:
- quizresults = open(chosenquiz + "_results.txt")
- average = open(chosenquiz + "_avgscore.txt")
- except IOError:
- print("No one has taken this quiz yet.")
- admin()
- avgscore = average.read()
- average.close()
- print("Average Score: " + avgscore)
- student_list = []
- score_list = []
- for line in quizresults:
- lines = line.split(": ")
- student = lines[0]
- score = int(lines[1])
- student_list.append(student)
- score_list.append(score)
- quizresults.close()
- top_score = max(score_list)
- top_student = student_list[score_list.index(top_score)]
- print(top_student + " achieved " + str(top_score) + ", the highest score.")
- with open(top_student + "_info.txt") as details:
- userinfo = details.read()
- print("The details of this user are:" + userinfo)
- admin()
- start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement