a82843fd71252daae3786fcdde9237b6aee7d11c
[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                 try:
13                     answer = input('? ')
14                 except EOFError:
15                     answer = 'quit'
16                 a = answer.strip().lower()
17                 if a in ['q', 'quit']:
18                     print()
19                     return
20                 if a in ['?', 'help']:
21                     print()
22                     print(question.prompt)
23                     print(question.hint)
24                     continue
25                 break
26             correct = self.process_answer(question=question, answer=answer)
27             if correct:
28                 print('correct\n')
29             else:
30                 print('incorrect\n')
31
32     def display_results(self):
33         print('results:')
34         for question in self.quiz:
35             for answer in self.answers.get(question.id, []):
36                 self.display_result(question=question, answer=answer)
37         self.display_totals()
38
39     def display_result(self, question, answer):
40         if answer['correct']:
41             correct = 'correct'
42         else:
43             correct = 'incorrect'
44         print('question:     {}'.format(question.prompt))
45         print('you answered: {}'.format(answer['answer']))
46         print('which was:    {}'.format(correct))
47         print()
48
49     def display_totals(self):
50         answered = self.answers.get_answered(questions=self.quiz)
51         correctly_answered = self.answers.get_correctly_answered(
52             questions=self.quiz)
53         la = len(answered)
54         lc = len(correctly_answered)
55         print('answered {} of {} questions'.format(la, len(self.quiz)))
56         print(('of the answered questions, {} ({:.2f}) were answered correctly'
57                ).format(lc, float(lc)/la))