Bonus: Let’s create a quiz!
Creating our quiz
Of course Tiramisu is great to handle options, but here’s a little thing you can do if you’re just bored and don’t know what to do.
So, let’s create a quiz.
First, as always, let’s import everything we need from Tiramisu and create our options:
1from sys import exit
2from tiramisu import (MetaConfig, Config, OptionDescription,
3 BoolOption, ChoiceOption, StrOption, IntOption,
4 Calculation, Params, ParamOption,
5 default_storage, list_sessions)
6from tiramisu.error import ConflictError
We make a dictionary with all questions, proposals and answer:
1questions = [{'description': 'what does the cat say?',
2 'proposal': ('woof', 'meow'),
3 'answer': 'meow'},
4 {'description': 'what do you get by mixing blue and yellow?',
5 'proposal': ('green', 'red', 'purple'),
6 'answer': 'green'},
7 {'description': 'where is Bryan?',
8 'proposal': ('at school', 'in his bedroom', 'in the kitchen'),
9 'answer': 'in the kitchen'},
10 {'description': 'which one has 4 legs and 2 wings?',
11 'proposal': ('a wyvern', 'a dragon', 'a wyrm', 'a drake'),
12 'answer': 'a dragon'},
13 {'description': 'why life?',
14 'proposal': ('because', 'I don\'t know', 'good question'),
15 'answer': 'good question'},
16 ]
Now build our Config.
We have to create question option.
Just after, we’re going to define the correct answer in a second option.
The answer is frozen so that when it is set, it cannot change.
And finally a last option that will verify if the answer is correct.
1options_obj = [] 2results_obj = [] 3for idx, question in enumerate(questions): 4 idx += 1 5 choice = ChoiceOption('question', 6 question['description'], 7 question['proposal']) 8 answer = StrOption('answer', 9 f'Answer {idx}', 10 default=question['answer'], 11 properties=('frozen',)) 12 boolean = BoolOption('verif', 13 f'Verif of question {idx}', 14 Calculation(verif, 15 Params((ParamOption(choice), 16 ParamOption(answer)))), 17 properties=('frozen',)) 18 optiondescription = OptionDescription(f'question_{idx}', 19 f'Question {idx}', 20 [choice, answer, boolean]) 21 options_obj.append(optiondescription) 22 results_obj.append(ParamOption(boolean))
The verif option will us a function that will verify if the answer given by the user
(which will become the value of question) is the same as the correct answer (which is the value
of answer). Here is this function (of course you have to declare at the begining of your code,
before your options) :
1def verif(q: str, a: str):
2 return q == a
Pretty simple.
At least we’re done with our questions. Let’s just create one last option. This option calculate the result of the students’ answers:
1def results(*verif):
2 return sum(verif)
3options_obj.append(IntOption('res',
4 'Quiz results',
5 Calculation(results,
6 Params(tuple(results_obj)))))
Now we just have to create our OptionDescription and Config (well it’s a MetaConfig here, but we’ll see this later)…
1rootod = OptionDescription('root', '', options_obj)
2default_storage.setting(engine="sqlite3")
3meta_cfg = MetaConfig([], optiondescription=rootod, persistent=True, session_id="quiz")
… and add some loops to run our quiz!
1def run_quiz(meta_cfg: MetaConfig):
2 pseudo = input("Enter a name: ")
3 try:
4 cfg = meta_cfg.config.new(pseudo, persistent=True)
5 except ConflictError:
6 print(f'Hey {pseudo} you already answered the questionnaire')
7 exit()
8 cfg.property.read_write()
9
10 for idx, question in enumerate(cfg.option.list(type='optiondescription')):
11 question_id = question.option.doc()
12 question_obj = question.option('question')
13 question_doc = question_obj.option.doc()
14 print(f'{question_id}: {question_doc}')
15 print(*question_obj.value.list(), sep=" | ")
16 while True:
17 input_ans = input('Your answer: ')
18 try:
19 question_obj.value.set(input_ans)
20 except ValueError as err:
21 err.prefix = ''
22 print(err)
23 else:
24 break
25 if question.option('verif').value.get() is True:
26 print('Correct answer!')
27 else:
28 print("Wrong answer... the correct answer was:", question.option('answer').value.get())
29 print('')
30 qno = idx + 1
31 print("Correct answers:", cfg.option('res').value.get(), "out of", qno)
32 if cfg.option('res').value.get() == 0 :
33 print("Ouch... Maybe next time?")
34 elif cfg.option('res').value.get() == qno :
35 print("Wow, great job!")
Display results for teacher:
1def quiz_results(meta_cfg: MetaConfig):
2 for cfg in meta_cfg.config.list():
3 print(f"==================== {cfg.config.name()} ==========================")
4 for idx, question in enumerate(cfg.option.list(type='optiondescription')):
5 if question.option('verif').value.get() is True:
6 answer = "correct answer"
7 else:
8 answer = "wrong answer: " + str(question.option('question').value.get())
9 print(question.option.doc() + ': ' + answer)
10 qno = idx + 1
11 print(f'{cfg.config.name()}\'s score: {cfg.option("res").value.get()} out of {qno}')
Now let’s play !
# reload old sessions
for session_id in list_sessions():
# our meta config is just here to be a base, so we don't want its session id to be used
if session_id != "quiz":
meta_cfg.config.new(session_id, persistent=True)
while True:
who = input("Who are you? (a student | a teacher): ")
if who in ['a student', 'a teacher']:
break
if who == 'a student':
run_quiz(meta_cfg)
else:
quiz_results(meta_cfg)
Download the full code
Hey, that was easy ! Almost like I already knew the answers… Oh wait…
Get players results
Now that you have your quiz, you can play with friends! And what’s better than playing with friends? Crushing them by comparing your scores of course! You may have noticed that the previous code had some storage instructions. Now we can create a score board that will give each player’s latest score with their errors !
We created a meta config that will be used as a base for all configs we will create : each time a new player name will be entered, a new config will be created, with the new player’s name as it’s session id. This way, we can see every player’s result !
So, earlier, we created a MetaConfig, and set the storage on sqlite3, so our data will not be deleted after the quiz stops to run.
Let’s run the script:
Who are you? (a student | a teacher): a studentEnter a name: my nameQuestion 1: what does the cat say?woof | meowYour answer: meowCorrect answer!Question 2: what do you get by mixing blue and yellow?green | red | purpleYour answer: greenCorrect answer!Question 3: where is Bryan?at school | in his bedroom | in the kitchenYour answer: at schoolWrong answer… the correct answer was: in the kitchenQuestion 4: which one has 4 legs and 2 wings?a wyvern | a dragon | a wyrm | a drakeYour answer: a dragonCorrect answer!Question 5: why life?because | I don’t know | good questionYour answer: good questionCorrect answer!Correct answers: 4 out of 5
When the quiz runs, we will create a new Config in our MetaConfig:
1def run_quiz(meta_cfg: MetaConfig): 2 pseudo = input("Enter a name: ") 3 try: 4 cfg = meta_cfg.config.new(pseudo, persistent=True) 5 except ConflictError: 6 print(f'Hey {pseudo} you already answered the questionnaire')
All results are store in this config (so in the database). So we need to reload those previous config:
1# reload old sessions 2for session_id in list_sessions(): 3 # our meta config is just here to be a base, so we don't want its session id to be used 4 if session_id != "quiz": 5 meta_cfg.config.new(session_id, persistent=True)
Later, a teacher ca display all those score:
Who are you? (a student | a teacher): a teacher==================== my name ==========================Question 1: correct answerQuestion 2: correct answerQuestion 3: wrong answer: at schoolQuestion 4: correct answerQuestion 5: correct answermy name’s score: 4 out of 5
You’ve got everything now, so it’s your turn to create your own questions and play with your friends !