Menu
CoddyTech

Bắt đầu

Bài học 8 trên 11 trong khóa học Dự án Python OOP: tạo trắc nghiệm của Coddy.

challenge icon

Thử thách

Trung bình

Thêm phương thức start, không nhận đầu vào, vào lớp Quiz. Phương thức này sẽ hiển thị các câu hỏi (từ trường questions) và yêu cầu người dùng nhập câu trả lời.

Xem các test case để hiểu rõ hơn về định dạng, hãy dùng phương thức print của câu hỏi.

Mỗi lời nhắc nhập liệu phải bắt đầu bằng '[+] ', hãy xem gợi ý nếu bạn chưa chắc cách thực hiện!

Lưu ý khoảng trắng và dòng mới!

Tự làm thử

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


class Quiz:
    def __init__(self, questions):
        self.questions = questions

Tất cả bài học trong Dự án Python OOP: tạo trắc nghiệm

Tự luyện tập: Trình biên dịch Python online