-
Notifications
You must be signed in to change notification settings - Fork 0
/
project.py
133 lines (104 loc) · 3.19 KB
/
project.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import json
from random import shuffle
import sys
def main():
filename = get_filename(sys.argv)
quiz = get_quiz(filename)
score = run_quiz(quiz)
show_result(score, quiz["scores"])
def get_filename(argv):
if len(argv) < 2:
sys.exit("Usage: python project.py \x1B[3m" + "quiz.json" + "\x1B[0m")
elif len(argv) > 2:
sys.exit("Usage: python project.py \x1B[3m" + "quiz.json" + "\x1B[0m")
else:
return argv[1]
def get_quiz(filename):
if filename[filename.rfind(".") + 1 :] != "json":
sys.exit(filename + " is not a .json file")
try:
file = open(filename, "r")
except FileNotFoundError:
sys.exit(filename + " does not exist")
try:
quiz = json.loads(file.read())
except json.JSONDecodeError:
file.close()
sys.exit("Incorrect file format")
else:
file.close()
return quiz
def run_quiz(quiz):
print(hr())
print(f"QUIZ: {quiz['title']}")
score = 0
total = len(quiz["questions"])
for index, question in enumerate(quiz["questions"], 1):
score += ask(index, total, question)
return score
def ask(index, total, question):
# os.system('clear')
print(hr())
print(f"Question {index} of {total}: {question['question']}\n")
shuffle(question["answers"])
for i, answer in enumerate(question["answers"], 1):
print(f"({i})", answer["answer"])
print()
while True:
try:
choice = int(input("Your answer? "))
except ValueError:
pass
try:
if 1 <= choice <= len(question["answers"]):
break
except UnboundLocalError:
pass
return int(question["answers"][choice - 1]["points"])
def show_result(score, scores):
scores = sorted(scores, key=lambda s: s["score"])
max_score = max(result["score"] for result in scores)
print(hr())
print(f"Your score: {score}/{max_score}\n")
for result in scores:
if score <= result["score"]:
print(result["result"])
break
print(hr())
def hr(symbol="─", times=120):
return symbol * times
# TODO: Take input from user and save quiz to file
def create_quiz():
quiz = {}
quiz["title"] = input("Title: ")
questions = []
while True:
question = {}
question["question"] = input("Question: ")
if question["question"] != "":
answers = []
while True:
answer = input("Answer: ")
if answer != "":
points = input("Points: ")
answers.append({"answer": answer, "points": int(points)})
else:
break
question["answers"] = answers
questions.append(question)
else:
break
quiz["questions"] = questions
scores = []
while True:
result = input("Result: ")
if result != "":
points = int(input("Score: "))
scores.append({"score": points, "result": result})
else:
break
quiz["scores"] = scores
# TODO: Save to file instead
print(json.dumps(quiz, indent=4))
if __name__ == "__main__":
main()