Menu
CoddyTech

Kuis

Pelajaran 7 dari 11 dalam kursus Generator Kuis: Proyek OOP Python di Coddy.

challenge icon

Tantangan

Mudah

Buat class Quiz.

Class ini akan mengoordinasikan pertanyaan.

 

Mari mulai dengan menambahkan konstruktor ke Quiz, konstruktor ini akan menerima list pertanyaan (class Question) dan menyimpannya dalam field bernama questions.

Coba sendiri

from abc import ABC, abstractmethod


class Question(ABC):
    @abstractmethod
    def print(self):
        pass

    @abstractmethod
    def check(self, answer):
        pass


class YesNoQuestion(Question):
    def __init__(self, question, answer):
        self.question = question
        self.answer = answer

    def print(self):
        print('[?] ' + self.question + ' (yes/no)')
    
    def check(self, answer):
        return (answer == 'yes' and self.answer) or \
            (answer == 'no' and not self.answer)


class OpenQuestion(Question):
    def __init__(self, question, answers):
        self.question = question
        self.answers = answers

    def print(self):
        print('[?] ' + self.question)
    
    def check(self, answer):
        return answer in self.answers


class MultiOptionsQuestion(Question):
    def __init__(self, question, options, answer_index):
        self.question = question
        self.options = options
        self.answer_index = answer_index

    def print(self):
        print('[?] ' + self.question)
        print()
        for i in range(len(self.options)):
            print('[' + str(i + 1) + '] ' + self.options[i])
    
    def check(self, answer):
        return self.answer_index == int(answer) - 1

Semua pelajaran di Generator Kuis: Proyek OOP Python

Latihan sendiri: Compiler Python online