Third Python Project: Quiz game

I reviewed the concepts of object-oriented programming that I learned in college, 

and I studied how to apply object-oriented principles by coding a simple game in python

 

This time, while studying object-oriented programming in Python,

I learned why the `__init__` method is necessary when creating objects.

 

Here's why the __init__ method is important:

1. It allows you to define and initialize the attributes (variables) of the object.

    Without __init__, you'd have to manually set up each attribute after creating an object, which could be error-prone.
2. You can customize the behavior of objects right from the start by passing different arguments

     to the __init__ method, leading to different initial states.

 

I also learned about the benefits of using `from ~~ import ~~`.

1. The reason for using the from import statement is to allow you to import and

    use only the specific parts you need from a module or package.

    This approach lets you select individual functions, classes, or variables without importing the entire module.

 

     For example, if you use import math, you have to access functions with the module name, like math.sqrt().

     However, with from math import sqrt, you can directly use sqrt() without the module prefix.

 

 

Here is game code

 

main.py

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

question_bank = []
for question in question_data:
    question_text = question["text"]
    question_answer = question["answer"]
    new_question = Question(q_text = question_text, q_answer = question_answer)
    question_bank.append(new_question)
    
quiz = QuizBrain(question_bank)

while quiz.still_has_question():
    quiz.next_question()

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

 

data.py

question_data = [
{"text": "A slug's blood is green.", "answer": "True"},
{"text": "The loudest animal is the African Elephant.", "answer": "False"},
{"text": "Approximately one quarter of human bones are in the feet.", "answer": "True"},
{"text": "The total surface area of a human lungs is the size of a football pitch.", "answer": "True"},
{"text": "In West Virginia, USA, if you accidentally hit an animal with your car, you are free to take it home to eat.", "answer": "True"},
{"text": "In London, UK, if you happen to die in the House of Parliament, you are entitled to a state funeral.", "answer": "False"},
{"text": "It is illegal to pee in the Ocean in Portugal.", "answer": "True"},
{"text": "You can lead a cow down stairs but not up stairs.", "answer": "False"},
{"text": "Google was originally called 'Backrub'.", "answer": "True"},
{"text": "Buzz Aldrin's mother's maiden name was 'Moon'.", "answer": "True"},
{"text": "No piece of square dry paper can be folded in half more than 7 times.", "answer": "False"},
{"text": "A few ounces of chocolate can to kill a small dog.", "answer": "True"}
]

 

question_model.py

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

 

quiz_brain.py

class QuizBrain():
    def __init__(self, q_list):
        self.question_number = 0
        self.score = 0
        self.question_list = q_list
        
    def still_has_question(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)
        
    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}")

 

When comparing my code with the example solution, I noticed a significant difference. 

In the `still_has_question()` method, I used an `if` statement to return `True` or `False`, 

whereas the example code used a `return` statement to write the code more concisely. 

 

After reading the example, I realized that using a `return` statement with a comparison operator directly 

returns `True` if the condition is met, and `False` otherwise. 

This approach makes the code function the same as mine, but in a cleaner and more efficient way.

 


How should I modify the code to use new quiz data fetched from an API on a quiz website?

 

If I want to utilize new quiz data fetched from an API on a quiz website,

I should modify the parameters used when creating the Question object to match the new data format.

 

For example, I processed the data using ["text", "answer"],

I should now adapt it to the new format, such as ["question", "correct_answer"].

This change is necessary due to the nature of modular object-oriented programming.

Even though the data format has changed,

the QuizBrain module will still function correctly with minimal modifications,

as it interacts with the Question object to handle the quiz data.

This is one of the main advantages of object-oriented programming.