Use question.id instead of question.prompt for answer indexing
[quizzer.git] / quizzer / ui / cli.py
1 from . import UserInterface
2
3
4 class CommandLineInterface (UserInterface):
5     def run(self):
6         while True:
7             question = self.get_question()
8             if not question:
9                 break
10             print(question.prompt)
11             while True:
12                 answer = input('? ')
13                 a = answer.strip().lower()
14                 if a in ['q', 'quit']:
15                     print()
16                     return
17                 if a in ['?', 'help']:
18                     print()
19                     print(question.prompt)
20                     print(question.hint)
21                     continue
22                 break
23             correct = self.process_answer(question=question, answer=answer)
24             if correct:
25                 print('correct\n')
26             else:
27                 print('incorrect\n')
28
29     def display_results(self):
30         print('results:')
31         for question in self.quiz:
32             for answer in self.answers.get(question.id, []):
33                 self.display_result(question=question, answer=answer)
34         self.display_totals()
35
36     def display_result(self, question, answer):
37         if answer['correct']:
38             correct = 'correct'
39         else:
40             correct = 'incorrect'
41         print('question:     {}'.format(question.prompt))
42         print('you answered: {}'.format(answer['answer']))
43         print('which was:    {}'.format(correct))
44         print()
45
46     def display_totals(self):
47         answered = self.answers.get_answered(questions=self.quiz)
48         correctly_answered = self.answers.get_correctly_answered(
49             questions=self.quiz)
50         la = len(answered)
51         lc = len(correctly_answered)
52         print('answered {} of {} questions'.format(la, len(self.quiz)))
53         print(('of the answered questions, {} ({:.2f}) were answered correctly'
54                ).format(lc, float(lc)/la))