# Day17 - The Quiz Project & the Benefit of OOP

**URL:** https://vip.studycamp.tw/t/day17-the-quiz-project-the-benefit-of-oop/3250
**Category:** Python 百日馬第二屆
**Tags:** 上課筆記
**Created:** [2022年三月27日 07:34 UTC](https://vip.studycamp.tw/t/day17-the-quiz-project-the-benefit-of-oop/3250 "2022-03-27T07:34:11Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![postman](https://vip.studycamp.tw/user_avatar/vip.studycamp.tw/postman/32/5624_2.png) [@postman](https://vip.studycamp.tw/u/postman)
#### Post date: [2022年三月27日 07:34 UTC](https://vip.studycamp.tw/t/day17-the-quiz-project-the-benefit-of-oop/3250/1 "2022-03-27T07:34:11Z")

</div>

## Goal: what we will make by the end of the day

## How to create your own Class in Python

1. Naming convention

補充:

> **[Naming Conventions - How to Write Beautiful Python Code With PEP 8 – Real Python](https://realpython.com/python-pep8/#naming-conventions)**
>
> “Explicit is better than implicit.” | Learn how to write high-quality, readable code by using the Python style guidelines laid out in PEP 8. Following these guidelines helps you make a great impression when sharing your work with potential employers...

![](https://remarkable-discovery-fb8.notion.site/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2Fefad56f4-b200-48fe-9d94-719bee2e2292%2FUntitled.png?table=block&id=2f194c5f-4117-4a54-bfd5-223c9868a1f1&spaceId=3235c93a-c6b6-4cd1-bd2c-e84975ff85f2&width=1420&userId=&cache=v2)

1. Class initialize

2. Working with Attributes : Class Constructions and the \_\_ init \_\_ () function

補充: **How to Write Beautiful Python Code With PEP 8**

> **[How to Write Beautiful Python Code With PEP 8 – Real Python](https://realpython.com/python-pep8/)**
>
> Learn how to write high-quality, readable code by using the Python style guidelines laid out in PEP 8. Following these guidelines helps you make a great impression when sharing your work with potential employers and collaborators.

> **[PEP 8 – Style Guide for Python Code | peps.python.org](https://peps.python.org/pep-0008/)**
>
> This document gives coding conventions for the Python code comprising the standard library in the main Python distribution. Please see the companion informational PEP describing style guidelines for the C code in the C implementation of Python.

補充:

> **[\[Python物件導向\]淺談Python類別(Class)](https://www.learncodewithmike.com/2020/01/python-class.html)**
>
> Photo by Bram Naus on Unsplash 在學習程式語言時，或多或少都有聽過物件導向程式設計 (Object-oriented programming ，簡稱 OOP) ，它是一個具有物件 (Object) 概念的開發方式，能夠提高軟體的重用性、擴充...

> **[Amazon.com: The Unified Modeling Language User Guide: 9780321267979: Booch,...](https://www.amazon.com/-/zh_TW/Unified-Modeling-Language-User-Guide/dp/0321267974)**
>
> Amazon.com: The Unified Modeling Language User Guide: 9780321267979: Booch, Grady, Rumbaugh, James, Jacobson, Ivar: 圖書

## The Quiz Project - Sequence Diagram for OOP

![](https://remarkable-discovery-fb8.notion.site/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F0c662d8b-42bb-4f7a-a435-a000849616db%2FUntitled.png?table=block&id=b1f89ee1-4567-45e3-b806-77fe8702588a&spaceId=3235c93a-c6b6-4cd1-bd2c-e84975ff85f2&width=1440&userId=&cache=v2)

補充說明:

> **[類別圖](https://zh.wikipedia.org/wiki/%E9%A1%9E%E5%88%A5%E5%9C%96)**
>
> 類別圖是軟體工程的統一建模語言一種靜態結構圖，該圖描述了系統的類別集合，類別的屬性和類別之間的關係。
> 類別圖是物件導向式的建模。他們一般都被用於概念建模（conceptual modelling）的系統分類的應用程式，並可將模型建模轉譯成程式碼。
> 為了進一步描述系統的行為，這些類圖可以輔之以狀態圖或UML狀態機。
> UML提供機制，以代表類的成員，如屬性和方法，對他們的其他資訊。

![](https://remarkable-discovery-fb8.notion.site/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F6ec57d96-ab31-4189-b377-f082e1509a4c%2FUntitled.png?table=block&id=02de7a5a-69d2-4e73-a140-c609f6769ca5&spaceId=3235c93a-c6b6-4cd1-bd2c-e84975ff85f2&width=1420&userId=&cache=v2)

data.py

> #Target to create lots of Question objects and then put them into a list like this.
> 
> question\_bank = [
> 
> ```
> Question(q1, a1),
> 
> Question(q2, a2),
> 
> Question(q3, a3),
> 
> ...
> 
> ```
> 
> ]

```python
question_data = [
    {
        "category": "Science: Computers",
        "type": "boolean",
        "difficulty": "medium",
        "question": "The HTML5 standard was published in 2014.",
        "correct_answer": "True",
        "incorrect_answers": [
            "False"
        ]
    },
    {
        "category": "Science: Computers",
        "type": "boolean",
        "difficulty": "medium",
        "question": "The first computer bug was formed by faulty wires.",
        "correct_answer": "False",
        "incorrect_answers": [
            "True"
        ]
    },
    {
        "category": "Science: Computers",
        "type": "boolean",
        "difficulty": "medium",
        "question": "FLAC stands for 'Free Lossless Audio Condenser'.",
        "correct_answer": "False",
        "incorrect_answers": [
            "True"
        ]
    },
    {
        "category": "Science: Computers",
        "type": "boolean",
        "difficulty": "medium",
        "question": "All program codes have to be compiled into an executable file in order to be run. This file can then be executed on any machine.",
        "correct_answer": "False",
        "incorrect_answers": [
            "True"
        ]
    },
    {
        "category": "Science: Computers",
        "type": "boolean",
        "difficulty": "easy",
        "question": "Linus Torvalds created Linux and Git.",
        "correct_answer": "True",
        "incorrect_answers": [
            "False"
        ]
    },
    {
        "category": "Science: Computers",
        "type": "boolean",
        "difficulty": "easy",
        "question": "The programming language 'Python' is based off a modified version of 'JavaScript'",
        "correct_answer": "False",
        "incorrect_answers": [
            "True"
        ]
    },
    {
        "category": "Science: Computers",
        "type": "boolean",
        "difficulty": "medium",
        "question": "AMD created the first consumer 64-bit processor.",
        "correct_answer": "True",
        "incorrect_answers": [
            "False"
        ]
    },
    {
        "category": "Science: Computers",
        "type": "boolean",
        "difficulty": "easy",
        "question": "'HTML' stands for Hypertext Markup Language.",
        "correct_answer": "True",
        "incorrect_answers": [
            "False"
        ]
    },
    {
        "category": "Science: Computers",
        "type": "boolean",
        "difficulty": "easy",
        "question": "In most programming languages, the operator ++ is equivalent to the statement '+= 1'.",
        "correct_answer": "True",
        "incorrect_answers": [
            "False"
        ]
    },
    {
        "category": "Science: Computers",
        "type": "boolean",
        "difficulty": "hard",
        "question": "The IBM PC used an Intel 8008 microprocessor clocked at 4.77 MHz and 8 kilobytes of memory.",
        "correct_answer": "False",
        "incorrect_answers": [
            "True"
        ]
    }
]

```

question\_model.py

```python
'''Quiz: Project Part1: Creating the Questions Class'''
class Questions:
	def __init__ (self,text,answer):
		self.text = text
		self.answer = answer
		

```

question\_model.py

```python
class Question:
    def __init__ (self, q_text, q_answer):
        self.text = q_text
        self.answer = q_answer
		

```

quiz\_brain.py

```python
class QuizBrain:

    def __init__ (self, q_list):
        self.question_number = 0
        self.score = 0
        self.question_list = q_list

    def still_has_questions(self):
        return self.question_number < len(self.question_list)
    
    def next_question(self):
        current_question = self.question_list[self.question_number]
        self.question_number += 1
        user_answer = input(f"Q.{self.question_number}: {current_question.text} (True/False): ")
        self.check_answer(user_answer, current_question.answer)
    
    '''Quiz Project Part5: Checking Answers and Keeping Score'''
    def check_answer(self, user_answer, correct_answer):
        if user_answer.lower() == correct_answer.lower():
            self.score += 1
            print("You got it right!")
        else:
            print("That's wrong.")
        print(f"The correct answer was: {correct_answer}.")
        print(f"Your current score is: {self.score}/{self.question_number}")
        print("\n")
		

```

main.py

```python
from question_model import Question
from data import question_data
from quiz_brain import QuizBrain

'''Quiz Project Part2: Creating the List of Question Objects from the Data'''

question_bank = []
for question in question_data:
    question_text = question["question"]
    question_answer = question["correct_answer"]
    new_question = Question(question_text, question_answer)
    question_bank.append(new_question)

'''Quiz Project Part3: The QuizBrian and the next_question() method'''
quiz = QuizBrain(question_bank)

'''Quiz Project Part 4: How to continue showing new Questions'''
while quiz.still_has_questions():
    quiz.next_question()

print("You've completed the quiz")
print(f"Your final score was: {quiz.score}/{quiz.question_number}")
		

```

補充:

## The Benefits of OOP: Use Open Trivia DB to Get New Questions

1. Open Trivia DB provides API for retrieve dynamic Question

> **[Open Trivia DB](https://opentdb.com/api_config.php)**
>
> Free to use, user-contributed trivia questions!

1. Generate API URL

[**Generate API URL**](https://opentdb.com/api.php?amount=10&category=23&difficulty=easy&type=boolean)

1. Python Internet Access using Urllib.Request and urlopen()

> **[Python Internet Access using Urllib.Request and urlopen()](https://www.guru99.com/accessing-internet-data-with-python.html)**
>
> In this tutorial, learn how to access Internet data in Python. Learn how to get HTML Data from URL using Urllib.Request and urlopen() examples.

webdata.py (my code)

**#透過API改寫資料源串接**

```python
import urllib.request as req
import ssl
import json

def getOpenData():
    #use ssl module to pass htttps certification
    ssl._create_default_https_context = ssl._create_unverified_context
    response = req.urlopen('https://opentdb.com/api.php?amount=10&category=23&difficulty=easy&type=boolean')
    #get the result code and print it, if normal response code is 200
    print ("result code: " + str(response.getcode()))

    # read the data from the URL and print it, here data type is bytes
    #data = str(response.read())
    #make bytes data and transform as dictionary object
    data = json.loads(response.read().decode('utf-8'))
    #{[{[]}]} ==> 題庫的資料結構, 需要抽絲剝繭
    #print(type(data['results']))
    data_002 = [i for i in data['results']]
    #print(data_002)
    return data_002

if __name__ == " __main__":
    getOpenData()
		

```

main.py (my code)

**#抽換成我改寫的WEB API**

#改寫Angela的主程式只有很簡單的改了題庫相關的2行程式碼 (\<=====部分)

```python
from question_model import Question
from data import question_data
from webdata import getOpenData # <===== 修改本行 <=====
from quiz_brain import QuizBrain

question_bank = []
#rewirte data module as webdata module for reterive question DB via web API
for question in getOpenData(): # <===== 修改本行 <=====
    question_text = question["question"]
    question_answer = question["correct_answer"]
    new_question = Question(question_text, question_answer)
    question_bank.append(new_question)

quiz = QuizBrain(question_bank)

while quiz.still_has_questions():
    quiz.next_question()

print("You've completed the quiz")
print(f"Your final score was: {quiz.score}/{quiz.question_number}")
		

```

資料來源：本文源自 [**Brad Chao Notion 筆記**](https://remarkable-discovery-fb8.notion.site/Python-100-days-course-Day17-b886903e785d4f96b875fb0e707f805d)，感謝授權轉載。
