반응형
이번엔 OOP를 이용해 퀴즈 생성기를 만들어 보았다.
OOP 들어오고 나서부터 조금씩 어려워지고 있는 것 같다. 그래도 얼추 이해가 돼서 다행이다.
로직
- dir 구성은 data.py, main.py, question_model.py, quiz_brain.py 로 구성 되어있다.
- data.py : 실제 문제 값이 dict 형태로 되어 있으며 키는 text 와 answer 로 되어 있다.
- main.py : 문제를 반복하는 로직과 그 외 question_model 과 quiz_brain 의 객체를 활용하는 코드를 작성 했다.
- question_model.py : 문제를 던져줄 수 있는 객체 틀을 만들어 놓았다.
- quiz_brain.py : 데이터를 받아서 여러 메소드를 통해 실질적으로 문제를 내주는 모듈이다.
코드
data.py
question_data = [
{
"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": "easy",
"question": "The logo for Snapchat is a Bell.",
"correct_answer": "False",
"incorrect_answers": ["True"]
},
{
"category": "Science: Computers",
"type": "boolean",
"difficulty": "easy",
"question": "Pointers were not used in the original C programming language; they were added later on in C++.",
"correct_answer": "False",
"incorrect_answers": ["True"]
},
{
"category": "Science: Computers",
"type": "boolean",
"difficulty": "easy",
"question": "RAM stands for Random Access Memory.",
"correct_answer": "True", "incorrect_answers": ["False"]
},
{
"category": "Science: Computers",
"type": "boolean",
"difficulty": "easy",
"question": "Ada Lovelace is often considered the first computer programmer.",
"correct_answer": "True", "incorrect_answers": ["False"]
},
{
"category": "Science: Computers",
"type": "boolean",
"difficulty": "easy",
"question": "Time on Computers is measured via the EPOX System.",
"correct_answer": "False",
"incorrect_answers": ["True"]
},
{
"category": "Science: Computers",
"type": "boolean",
"difficulty": "easy",
"question": "The Windows ME operating system was released in the year 2000.",
"correct_answer": "True",
"incorrect_answers": ["False"]
},
{
"category": "Science: Computers",
"type": "boolean",
"difficulty": "easy",
"question": "Linux was first created as an alternative to Windows XP.",
"correct_answer": "False",
"incorrect_answers": ["True"]
},
{
"category": "Science: Computers",
"type": "boolean",
"difficulty": "easy",
"question": "The Python programming language gets its name from the British comedy group 'Monty Python.'",
"correct_answer": "True", "incorrect_answers": ["False"]
}
]
main.py
## O/X 게임 만들기
## 로직
# 1. 질문 클래스 만들기
# 2.
from data import question_data
from question_model import Question
from quiz_brain import QuizBrain
# Write a for loop to iterate over the question_data.
# Create a Question object from each entry in question_data.
# Append each Question object to the question_bank
question_bank = []
for i in question_data:
question = i["question"]
answer = i["correct_answer"]
new_q = Question(question, answer)
question_bank.append(new_q)
quiz = QuizBrain(question_bank)
while quiz.still_has_questions() :
quiz.next_question()
question_model.py
# Create a Question class with an __init__ method with two attributes: text and answer arttribute
class Question:
def __init__(self, q_text, q_answer):
self.text = q_text
self.answer = q_answer
quiz_brain.py
# asking the questions
# checking if the answer was correct
# checking if we're the end of the quiz
# Create a class called QuizBrain
class QuizBrain:
# Write an __init() method
# Initilalise the question_number to 0
# Initialise the question_list to an input.
def __init__(self, q_list):
self.question_number = 0
self.question_list = q_list
self.score = 0
def still_has_questions(self):
return self.question_number < len(self.question_list)
# Retrieve the item at the current question_number from the question_list.
# Use the input() function to show the Question text and ask for the user's answer
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)
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.")
# 리스트 length 만큼 반복하기
if self.question_number < len(self.question_list) :
print(f"The correct answer was: {correct_answer}.")
print(f"Your current score is : {self.score}/{self.question_number}.")
print("\n")
# 마지막 질문일 경우 다른 문자열 출력
elif self.question_number == len(self.question_list) :
print("You've completed the quiz")
print(f"Your final score was: {self.score}/{len(self.question_list)}")
3줄 요약
- 다음부터 로직 작성할 때 꼭 메소드는 Docstring 처리하거나 주석 처리 하기 (연습 필요할 듯)
- 클래스 내에서 선언한 속성 즉 __init__ 메소드에서 self. 으로 선언된 속성은 다른 메소드에서도 동일한 방법으로 이용 가능
- 꼭 if 문으로 조건 처리 할 것 없이 비교연산자일 경우 return+구문 으로 True / False 반환 가능
반응형
'프로그래밍 > Python' 카테고리의 다른 글
Python 부트 캠프 - turtle 모듈을 이용한 레이싱 경기 (0) | 2023.05.24 |
---|---|
Python 부트 캠프 - turtle 모듈을 이용한 소과제 해결하기 (0) | 2023.05.24 |
Python 부트 캠프 - OOP를 이용한 커피 머신 생성 (0) | 2023.05.21 |
Python 부트 캠프 - 커피 머신 생성 (2) | 2023.05.19 |
Python 부트 캠프 - 계산기 만들기 (0) | 2023.04.30 |