Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json #json.load(), json.dump()
- import time #time.sleep()
- import csv #csv.reader(), csv.writer()
- import sys #sys.exit()
- import os #os.path.isfile()
- import configparser #configparser.ConfigParser()
- import string #string.ascii_letters
- def start():
- user_input = input_checker("""1: Login
- 2: Register
- Please choose one of the above options: """,(1,2))
- option_selector((login,register),(1,2),user_input)()
- def input_checker(question, valid_inputs):
- user_input = input(question)
- while 1:
- while [i for i in valid_inputs if type(i) == int]:
- try:
- user_input = int(user_input)
- break
- except ValueError:
- user_input = input("Please enter a valid number: ")
- try:
- if not [x for x in user_input if x not in valid_inputs]:
- break
- user_input = input("Please enter a valid input: ")
- except TypeError:
- if user_input in valid_inputs:
- break
- user_input = input("Please enter a valid input: ")
- return user_input
- def option_selector(options,numbers,user_input):
- option_dict = dict(zip(numbers, options))
- return option_dict[user_input]
- def register():
- name = input_checker("Please enter your name: ",tuple(string.ascii_letters)).title()
- age = input_checker("Please enter your age (you must be 11-18 years old): ",tuple(range(11,19)))
- year_group = input_checker("Please enter your year group (7-13): ",tuple(range(7,14)))
- username = name[:3] + str(age)
- with open("users.csv") as u:
- users = u.read()
- while username in users:
- username += "1"
- print("Welcome {}, your username is: {}".format(name,username))
- password = input("Please create a password: ")
- user_details = (name,age,year_group,username,password)
- with open("users.csv","a") as u:
- writer = csv.writer(u)
- writer.writerow(user_details)
- print("You will now be prompted to login.")
- time.sleep(0.5)
- login()
- def login():
- given_username = input("Please enter your username: ").title()
- given_password = input("Please enter your password: ")
- config.read("config.ini")
- admin_password = config["quiz_settings"]["admin_password"]
- if given_username == "Teacher":
- if given_password == admin_password:
- admin()
- else:
- print("Incorrect password.")
- login()
- with open("users.csv") as user_file:
- reader = csv.reader(user_file)
- user_check = tuple(filter(lambda x: x and given_username == x[3],[row for row in reader]))
- if not user_check:
- user_input = input_checker("""The username you entered doesn't exist.
- 1: Try again
- 2: Register
- Please choose one of the above options to continue: """,[1,2])
- option_selector((login,register),(1,2),user_input)()
- else:
- user_details = user_check[0]
- password = user_details[4]
- if given_password == password:
- print("Welcome, " + given_username)
- with open("username.json","w") as u:
- json.dump(given_username, u)
- menu()
- else:
- print("Incorrect password.")
- login()
- def menu():
- with open("username.json") as u:
- username = json.load(u)
- subject,subjects,chosen_difficulty,difficulties = quiz_selector()
- with open("user_results.csv") as u:
- reader = csv.reader(u)
- user_check = [row for row in reader if row and row[0] == username]
- if len(user_check) == len(subjects) * len(difficulties):
- print("You have taken every quiz. You will now be logged out.")
- time.sleep(1)
- start()
- for result in user_check:
- if [subject,chosen_difficulty] == result[1:3]:
- print("You have already taken this quiz.")
- time.sleep(0.5)
- menu()
- quiz_file = subject.lower() + ".csv"
- score = quiz(quiz_file, chosen_difficulty)
- percentage = int(round((score/5) * 100))
- percentage_map = {0: 'E', 20: 'D', 40: 'C', 60: 'B', 80: 'A', 100: 'A*'}
- grade = percentage_map[percentage]
- print("""Your final score is: {}/5.
- Your percentage is: {}%.
- Your grade is: {}.""".format(str(score),str(percentage),grade))
- user_result = (username,subject,chosen_difficulty,str(score),grade)
- with open("user_results.csv","a") as u:
- writer = csv.writer(u)
- writer.writerow(user_result)
- user_input = input_checker("""1: Take another quiz
- 2: Logout
- Please choose one of the above options to continue: """,(1,2))
- option_selector((menu,start),(1,2),user_input)()
- def quiz_selector():
- config.read("config.ini")
- subjects = tuple(config["quiz_settings"]["subjects"].split(","))
- subject_index = []
- for i, topic in enumerate(subjects, start=1):
- print((i),": " + topic)
- subject_index.append(i)
- chosen_subject = input_checker("Please choose one of the above subjects: ",subject_index)
- subject = subjects[(subject_index.index(chosen_subject))]
- difficulty = input_checker("""1: Easy
- 2: Medium
- 3: Hard
- Please choose one of the above difficulties: """,(1,2,3))
- difficulties = ("easy","medium","hard")
- chosen_difficulty = difficulties[difficulty - 1]
- return subject,subjects,chosen_difficulty,difficulties
- def quiz(quiz_file,difficulty):
- with open(quiz_file) as q:
- reader = csv.reader(q)
- questions = [line for line in reader]
- difficulty_map = {"easy" : (0,5),
- "medium" : (5,10),
- "hard" : (10,15)}
- question_reader = difficulty_map[difficulty]
- quiz_questions = questions[(question_reader[0]):(question_reader[1])]
- score = 0
- for line in quiz_questions:
- x, question = line[0:2]
- answers = tuple(filter(lambda a: a != x and a != question, line))
- valid_answers = []
- print(question)
- for i, answer in enumerate(answers,start=1):
- print((i),": " + answer)
- valid_answers.append(i)
- user_answer = input_checker("Please choose one of the above answers: ",valid_answers)
- correct_answer = line[int(x)]
- correct_input = valid_answers[answers.index(correct_answer)]
- if user_answer == correct_input:
- print("Correct!")
- score += 1
- else:
- print("Sorry, the correct answer was: {}".format(str(correct_answer)))
- return score
- def admin():
- user_input = input_checker("""1: Check a user's results
- 2: Check the results for a quiz
- 3: Logout
- Please choose one of the above options to continue: """,(1,2,3))
- option_selector((user_report,quiz_report,start),(1,2,3),user_input)()
- def user_report():
- username = input("Please enter their username: ").title()
- with open("user_results.csv") as u:
- reader = csv.reader(u)
- user_result = [row for row in reader if row and username == row[0]]
- if not user_result:
- print("This user hasn't completed any quizzes.")
- admin()
- for result in user_result:
- print("""Subject: {}
- Difficulty: {}
- Score: {}
- Grade: {}\n""".format(result[1],result[2].title(),result[3],result[4]))
- admin()
- def quiz_report():
- subject,subjects,difficulty,difficulties = quiz_selector()
- with open("user_results.csv") as u:
- reader = csv.reader(u)
- user_result = [row for row in reader if row and [subject,difficulty] == row[1:3]]
- if not user_result:
- print("No-one has taken this quiz.")
- admin()
- total_score = 0
- for result in user_result:
- total_score += int(result[3])
- avg_score = round(total_score/len(user_result),1)
- print("The average score for this quiz is {}.".format(str(avg_score)))
- scores = sorted(user_result,key=lambda score: int(score[3]),reverse=True)
- highest_user = scores[0]
- with open("users.csv") as u:
- with open("users.csv") as user_file:
- reader = csv.reader(user_file)
- user = tuple(filter(lambda x: x and highest_user[0] == x[3],[line for line in reader]))
- user_details = user[0]
- print("""The highest score was {}, achieved by {}. The details of this user are:
- Name: {}
- Age: {}
- Year Group: {}""".format(highest_user[3],highest_user[0],user_details[0],user_details[1],user_details[2]))
- admin()
- config = configparser.ConfigParser()
- for x in ("users.csv","user_results.csv"):
- if not os.path.isfile(x):
- open(x,"w").close()
- if not os.path.isfile("config.ini"):
- config["quiz_settings"] = {"subjects": "Maths,Business","admin_password": "admin456"}
- with open("config.ini","w") as config_file:
- config.write(config_file)
- start()
Add Comment
Please, Sign In to add comment