CodeNewbie Community 🌱

Cover image for How to build a Quiz Game in Python
Rishabh Singh ⚡
Rishabh Singh ⚡

Posted on

How to build a Quiz Game in Python

Hello everyone, today we are going to create a fun Quiz Game in python.

How does it work?

Our quiz game will be asking questions to the player to which player has to reply with the right answer. Each question will have 3 attempts. If the player fails to answer the question within 3 attempts then the game will move on to the next question and the player will receive zero points. But if the player gives the right answer to the question then, he will get 1 point. At the end of the game, the total points scored by the player are displayed.

Alt Text

I hope the abstract working of the game is clear to everyone, now let's move on to the project setup.

Project Setup

Before we start coding this project, we need some questions and answers for our game.

In our case, we are going to use some easy superhero based questions.

Feel free to use your own questions or answers for the game. Our questions and answers will be stored in a separate python file in a form of a python dictionary.

Here how it looks:

quiz = {
    1 : {
        "question" : "What is the first name of Iron Man?",
        "answer" : "Tony"
    },
    2 : {
        "question" : "Who is called the god of lightning in Avengers?",
        "answer" : "Thor"
    },
    3 : {
        "question" : "Who carries a shield of American flag theme in Avengers?",
        "answer" : "Captain America"
    },
    4 : {
        "question" : "Which avenger is green in color?",
        "answer" : "Hulk"
    },
    5 : {
        "question" : "Which avenger can change it's size?",
        "answer" : "AntMan"
    },
    6 : {
        "question" : "Which Avenger is red in color and has mind stone?",
        "answer" : "Vision"
    }
}
Enter fullscreen mode Exit fullscreen mode

You can learn more about python dictionaries from here.

We won't be able to cover much about dictionaries in this tutorial but basically it is a data structure that can be used to store data as a single, organized & easy to access form.

You can think of the dictionary as the list. But there are some key differences between lists & dictionaries:

  • Lists are enclosed within () parenthesis while dictionaries are enclosed in {} brackets.
  • Individual elements of lists are accessed using index of the element while individual elements of dictionaries are accessed through key:value pair where key is the identifier and value is its corresponding data or value.

You must make sure that your dictionary should be in the same format as above or else you may need to make necessary changes to the code to make it work for you. Feel free to ask questions on my social handles or post your question below in discussions/comments.

Now I assume that you have your questions & answers ready. Make sure that your Q&A python file is in the same folder as your main quiz game python file which we will start coding in just a second.

Now let's jump to coding.

Let's Code

The first thing we always do is import required modules into our code. Luckily for this project, we don't need any specific module. However, we still need to import the Q&A python file we created in the previous step.

We have named our Q&A python file as questions.py. Here's how we will import it:

from questions import quiz
Enter fullscreen mode Exit fullscreen mode

We are asking python to import the quiz dictionary which contains our question & answers from the file questions.py.

Now let's get to the structure of our game...

Pay close attention! As this might feel a bit complicated...

Now we are going to initialize a variable to keep track of the score.

score = 0
Enter fullscreen mode Exit fullscreen mode

Now it's time to ask the questions to our player.

For that, we need to create an for loop which will iterate through all the questions.

# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    pass
Enter fullscreen mode Exit fullscreen mode

Now as previously mentioned, the player will have 3 attempts for each question to get the right answer.

Let's create a variable to keep track of the attempts.

# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    attempts = 3
Enter fullscreen mode Exit fullscreen mode

Now let's create an while loop within our for loop, which will run only until player has attempts left.

# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    attempts = 3
        # this while loop will run until player has more than 0 attempts left
        while attempts > 0:
                pass
Enter fullscreen mode Exit fullscreen mode

Great! Now let's print the questions and take the response from our player. We'll use our good old print() & input() functions for that.

# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    attempts = 3
        while attempts > 0: 
                print(quiz[question]['question']) # this will print the current interation of for loop
        answer = input("Enter Answer: ")
Enter fullscreen mode Exit fullscreen mode

Awesome! The response of the player will be stored in the answer variable.

Now we will use a function which will check if the answer provided by the player is right or wrong. We will name that function as check_ans(). For now, let's focus on our for loop and then we will see how this function works.

# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    attempts = 3
        while attempts > 0: 
                print(quiz[question]['question']) # this will print the current interation of for loop
        answer = input("Enter Answer: ")
                check = check_ans(question, answer, attempts, score)
Enter fullscreen mode Exit fullscreen mode

We will pass 4 parameters to our function, which are:

  • question - the current iteration of for loop
  • answer - the answer provided by player
  • attempts (optional) - an optional parameter of number of attempts left
  • score (optional) - an optional parameter of the current score of the player

We will store the output of our function in check variable.

Now we are going to use if statements to increase score if the answer provided by the player is right.

# Here remember 'quiz' is our dictionary and 'question' is our temp variable
for question in quiz:
    attempts = 3
        while attempts > 0: 
                print(quiz[question]['question']) # this will print the current interation of for loop
        answer = input("Enter Answer: ")
                check = check_ans(question, answer, attempts, score)
                if check:
            score += 1
            break
        attempts -= 1
Enter fullscreen mode Exit fullscreen mode

Here if the answer given by the player is right then the score will increase by 1 and the while loop will break and the for loop will move on to the next question.

But if the answer is wrong, then the player will lose one attempt, and the while loop will continue until either right answer is provided by the player or player runs out of attempts.

Here finally, our for loop ends!

Are we forgetting something? 🤔

Oh we forgot the implementation of our check_ans() function... Let's cover that quickly!

def check_ans(question, ans, attempts, score):
    if quiz[question]['answer'].lower() == ans.lower():
        return True
    else:
        return False
Enter fullscreen mode Exit fullscreen mode

Here is our function... Let's break it down!

Here an if statement will compare the answer provided by the player with the correct answer from our dictionary.

If the answer is right then it will return True or else it will return False.

Let's add a few print statements to notify the player if his answer is right or wrong.

def check_ans(question, ans, attempts, score):
    if quiz[question]['answer'].lower() == ans.lower():
        print(f"Correct Answer! \nYour score is {score + 1}!")
        return True
    else:
        print(f"Wrong Answer :( \nYou have {attempts - 1} left! \nTry again...")
        return False
Enter fullscreen mode Exit fullscreen mode

Here looks good right!

You did it! Be proud of yourself 🤩

Some Ideas to try out

Here are some quick ideas you can try with this project.

  • Make it multiplayer - Try modifying this game so that more than one player can enjoy this game at once. You can do this by simply adding an additional for loop which will contain the names of the players and score of each player is stored separately. The player with the highest score will win the game.
  • Use MCQ format - Not just quiz, you can also use it conduct MCQ tests. All you have to do is modify the print function to print the multiple answers and the player will have to guess the right answer.
  • Use an API - Make use of an interesting API to automatically fetch questions from the web so you don't have to get into the hassle of creating the questions and answers on your own. One of my favorite is the Superhero API.

Source Code

You can find the complete source code of this project here -

mindninjaX/Python-Projects-for-Beginners

Support

Thank you so much for reading! I hope you found this beginner project useful.

If you like my work please consider Buying me a Coffee so that I can bring more projects, more articles for you.

https://dev-to-uploads.s3.amazonaws.com/i/5irx7eny4412etlwnc64.png

Also if you have any questions or doubts feel free to contact me on Twitter, LinkedIn & GitHub. Or you can also post a comment/discussion & I will try my best to help you :D

Top comments (0)