Python 100 projects in 100 days — Learning Journal

Paul Zhao
Paul Zhao
Nov 25, 2020 · 5 min read

Day seventeen— Quiz project and how to take advantage of OOP (Object Oriented Programming)

Just your peace of mind, I would include installation for Python before we get started with our project

Here are a couple of ways you may put python in use.

1 Repl.it — Free registration and a bunch of features provided

2 Install Python locally (using Mac)

Installing Homebrew

Open terminal and type in

$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
.
.
.
==> Installation successful!==> Homebrew has enabled anonymous aggregate formulae and cask analytics.
Read the analytics documentation (and how to opt-out) here:
https://docs.brew.sh/Analytics
No analytics data has been sent yet (or will be during this `install` run).==> Homebrew is run entirely by unpaid volunteers. Please consider donating:
https://github.com/Homebrew/brew#donations==> Next steps:
- Run `brew help` to get started
- Further documentation:
https://docs.brew.sh

Verify Homebrew installation

$ brew --version
Homebrew 2.4.16
Homebrew/homebrew-core (git revision 23bea; last commit 2020-09-04)
Homebrew/homebrew-cask (git revision 5beb1; last commit 2020-09-05)

Once you’ve installed Homebrew, insert the Homebrew directory at the top of your PATH environment variable. You can do this by adding the following line at the bottom of your ~/.profile file

export PATH="/usr/local/opt/python/libexec/bin:$PATH"

2. Python (the version must be 3.7 to make sure that all functions will be available to present intended outcome) is required to be installed

Installing Python3

Now, we can install Python 3:

$ brew install python
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/cask).
==> Updated Casks
sessionWarning: python@3.8 3.8.5 is already installed and up-to-date
### my python was preinstalled, you may see different installation process. And it may take a while before python is fully installed

Verify is your python3 is installed

$ python3 --version
Python 3.8.5

Notes: you may set your default python as latest version by applying following code

$ unlink /usr/local/bin/python
$ ln -s /usr/local/bin/python3.8 /usr/local/bin/python

If using windows, please follow instruction below to install Chocolatey, then install Python using it

1 Install Chocolatey

2 Install Python

Let’s get started with our project now!

Today, we will build our whole project from scratch, let’s dive in!

Firstly, let us set our data.py file, we will update it later on to showcase the merits of our OOP (Objective Oriented Programming)

data.py

Step 1 Creating Question class:

in file named question_model.py

class Question:

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

Here we generate a initial function for the class named Question. In this function, we hold our text as q_text and answer as q_answer

Step 2 Creating the list of question objects from data:

In file name main.py

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

We create an empty list named question_bank. Then for any question in question_data, we assign the value of text and answer to question_text and question_answer respectively. After that, we create a new value named new_question which holds both question_text and question_answer. So each time we add a new_question to our question_bank by using .append function

Step 3 QuizBrain and the next_question() method:

In file named quiz_brain.py

class QuizBrain:

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

Firstly, we create a class named QuizBrain, then we set up initial function as shown above. Secondly, we create a value named self.question_number and assign it with 0, then generate another value named self.score and assign it with 0 as well. Lastly, we create a value named self.question_list and assign it with q_list

Then we go back to our main.py file and add following code

quiz = QuizBrain(question_bank)

What this provides us is the question_bank list we created in Step 2 will be thrown into QuizBrain, which indicates q_list is question_bank .

Now we tackle the next_question() method in our quiz_brain.py file

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)

In this function, we create a value named current_question and assign self.question_list[self.question_number] as its value, which indicates that we hold question_number in question_list to locate the current_question. Also, this self.question_number is increasing by 1 each time. Then the user_answer with be assigned with input(f”Q.{self.question_number}: {current_question.text} (True/False): “) . And the last line of code basically showcases that we we use both user_answer and current_question.answer to check out our answer, which we use create in the step 5

Step 4 How to continue showing new questions:

In quiz_brain.py file

def still_has_questions(self):
return self.question_number < len(self.question_list)

and in main.py file

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

Here we first create a while loop in main.py file to make sure that the loop continues as long as self.question_number < len(self.question_list) is True, which means question_number will be increasing with next_question() function from Step 3 until the number is equal to len(self.question_list) , then the while loop will be ended. But quiz.next_question() function we go continue generated new questions as long as the while loop is still going on

Step 5 Checking answers and keeping scores:

In quiz_brain.py file

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")

In main.py at the very end

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

In quiz_brain.py file, we create a function named check_answer and throw both user_answer and correct_answer into it to do the comparison. If user_answer.lower() == correct_answer.lower(): , then it means our answer is correct, so self.score should be added by 1. Otherwise, that’s wrong. Then we print out The correct answer was: {correct_answer}. and Your current score is: {self.score}/{self.question_number} using different variables created in earlier steps.

Ultimately, in main.py file, we have final score printed using self.score and self.question_number

Step 6 — Using Trivia DB to get news questions:

Here is you may find Trivia DB

our brand new data.py file

How should we update our existing to fit this data in?

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

We only need to update our question[“text”] and question[“answer”] with question[“question”] and question[“correct_answer”] respectively. Then the brand new questions and answers will fit in.

Final code for your convenience

main.py

question_model.py

quiz_brain.py

That’s all for another challenging day. As we move to OOP (Objective Oriented Programming), the logic behind our codes is getting more complex, let us dive in together and well challenge our brain to keep going!