Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

My quiz

my quiz (minus the boilerplate "questions")

import datetime
import random

from questions import *

class Quiz:
    questions = []
    # answers so we can pick with ones were wrong/right
    answers = []
    correct = []
    incorrect = []

    def __init__(self, num_questions=10, num_range=12, question_types=[Multiply]):
        # make 10 random questions
        for _ in range(num_questions):
            # get 2 random numbers, within the range we are testing except "1"
            nums = [random.choice(range(2, num_range)) for _ in range(2)]
            # pick between our options for question types
            q = random.choice(question_types)
            # instantiate our question object with numbers
            question = q(*nums)
            # add this question into self.questions
            self.questions.append(question)
        self.take_quiz()


    def take_quiz(self):
        print("WELCOME TO THE QUIZ! \n\n")
        # log the start time
        quiz_st_time = datetime.datetime.now()
        # ask all of the questions and store the responses
        for question in self.questions:
            self.answers.append(self.ask(question))
        # log if they got all the questions right
        self.correct = [q['correct'] for q in self.answers]
        self.incorrect = [q['correct'] for q in self.answers if not q['correct'] ]
        # log the end time
        quiz_fn_time = datetime.datetime.now()
        # show a summary
        return self.summary(start=quiz_st_time, finish=quiz_fn_time)

    def ask(self, question):
        # log the start time
        question_st_time = datetime.datetime.now()
        # capture the response
        response = input(question.text+" ")
        # convert to ints if we can
        try:
            answer = int(response)
        except ValueError:
            answer = response 
        # check the answer
        # if the answer is right, ret True, else False
        return {'question':     question.text,
                'answer':       answer,
                'correct':      answer==question.answer, 
                'elapsed_time': datetime.datetime.now() - question_st_time}


    def summary(self, start, finish):
        # print number right/wrong
        print("\nCorrect: {} Incorrect: {}\n".format(len(self.correct), len(self.incorrect)))
        for answer in self.answers:
            print("Question: {} Answer: {} Correct?: {} Seconds: {}".format(
                    answer['question'], 
                    answer['answer'], 
                    answer['correct'], 
                    answer['elapsed_time'].seconds))
        # print total quiz time
        print("Total time: {}m {}s".format((finish - start).seconds//60, (finish - start).seconds %60))

if __name__ == '__main__':
    Quiz()

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

Nicely done! I did notice a bug: Correct count is always 10. The creation of self.correct needs test condition:

        self.correct = [q['correct'] for q in self.answers if q['correct']]

In other feedback, The statements to count the number correct and incorrect seem overly complicated. You are building a list but only really need the length of the list, or more precisely, the count of each correctness. A simplified approach:

        # collect grades for analysis
        self.grades = [q['correct'] for q]
        self.correct = self.grades.count(True)
        self.incorrect = self.grades.count(False)
        # OR: self.incorrect = len(self.grades) - self.correct