-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
90 lines (78 loc) · 2.96 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import csv
import json
valid_symbols = "abcdefghijklmnopqrstuvwxyz"
correct_answer_count = 0
incorrect_answer_count = 0
total_questions = 10
valid_answers = ["a", "b", "c", "d"]
quiz_results = []
# username validation to prevent file creation errors
username = input("Please enter your name: ")
for symbol in username:
if symbol not in valid_symbols:
print("Please use only latin letters for your name.")
exit()
# this handler checks if the input is valid, and if the user wants to quit
def input_handler(user_input):
if user_input.strip().lower() == "quit" or user_input.strip().lower() == "exit":
print_results()
exit()
if user_input.strip().lower() not in valid_answers:
print("\nError: Invalid input.")
print("You should enter only one letter (a - d) corresponding to the answer.")
return False
return True
def calculate_score(correct_answer_count):
temp = correct_answer_count / total_questions * 100
if temp >= 90 or temp <= 100:
return "Excellent!"
elif temp >= 70 or temp < 90:
return "Good job!"
elif temp >= 50 or temp < 70:
return "You passed!"
else:
return "Better luck next time!"
def print_results():
print("The quiz is over!")
print(f"Results for user {username}:")
print(f"Correct answers: {correct_answer_count}")
print(f"Incorrect answers: {incorrect_answer_count}")
print(calculate_score(correct_answer_count))
def save_results_to_csv():
filename = username.lower().replace(" ", "_") + "_quiz_results.csv"
with open(filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Question Number", "Question Text", "User's Answer", "Correct Answer", "Result"])
writer.writerows(quiz_results)
print(f"Quiz results saved to {filename}")
with open("quiz.json", "r") as file:
quiz_json = json.load(file)
# main quiz logic
for key, value in quiz_json["quiz"].items():
# key[8:] is used to omit the "question" part in "question1", "question2" and so on
print(f"Question {key[8:]}:", value["question"])
for option, answer in value["options"].items():
print(option + ": " + answer)
user_input = input("Enter your answer: ")
# loop that requires the user to input a valid answer
while not input_handler(user_input):
user_input = input("Enter your answer: ")
# check the answer
if user_input.lower().strip() == value["correct_answer"]:
correct_answer_count += 1
is_correct = True
print("\nCorrect!\n")
else:
incorrect_answer_count += 1
is_correct = False
print("\nWrong answer.")
print(f"The correct answer is: {value["correct_answer"]}\n")
quiz_results.append([
key[8:],
value["question"],
user_input.lower().strip(),
value["correct_answer"],
"Correct" if is_correct else "Incorrect" # ternary operator
])
print_results()
save_results_to_csv()