Create Your own Quiz Game in Python (with CSV file)

This is a quiz game in Python. The data used in this game is stored in a csv file.

Introduction

Many of us like quizzes, many are experts on it. If you also like and you're a Pythonist, then this article gonna give you lots of fun because here we are going to create our own Quiz Game in Python.

Here, our quiz topics are related to the world. I know the number will be infinite if I try to pick questions on different topics from all over the world. Sounds ridiculous, right? No, we'll not do that.

For our convenience, I have collected a limited number of questions on several interesting topics to create this quiz game project.

Check the project details to understand the rationale better.

👉Visit AlsoNumber Guessing Game in Python - Guess between 1 and 100

the world

Project Details

The program asks the player some questions about general knowledge. They get four choices to answer each question. Each correct answer will score one point. If the player selects the wrong one then the program will display the message: "Wrong answer" and display the correct answer to the given question.

The program shows a total score based on the answers to 10 questions. Next, the player gets two options: "Want to play again or not". If the player selects YES they will get 10 more questions.

All the questions have been collected from the Web and stored in a CSV file. A total of 25 questions are there. I've shared the source link at the end of this tutorial. You can easily collect more questions from there and add them to the CSV file.

It's a CSV file of mcq questions related to world quiz. This file is used in a quiz game project in python.
Image - The CSV file of MCQ Questions

The data is stored in the CSV file according to the above format. There are four attributes(shown in yellow color) for four choices to each question, and one attribute is for the actual answer(shown in the green color). You can add more data to this file. I recommend you to add the data multiply of 10 always.

Requirements

Since we're discussing a python project here, it must be installed in your system. If already there is no problem. Otherwise, you don't need to install any extra modules to complete this python project.

We did enough chit-chat. Let's get straight to the main topic.

quiz

Import the CSV module

First, import the python CSV module and declare three variables for use in the upcoming code.


import csv

score = 0
line_count = 0
applied_ques = 0

Initialize a dictionary

Next, declare a Python Dictionary that stores four keys corresponding with four values for four multiple-choice questions.


options = {
'A': 1,
'B': 2,
'C': 3,
'D': 4
}

Build the check Function

The next task is to check if the option is correct or not, chosen by the player. The code creates a function check_guess(). It will check if the player chooses the right answer or not. If the answer is correct, it shows a message and updates the 'score' variable by adding 1 with it.

If the answer is wrong, it will show another message. Lastly, it updates the 'applied_ques' variable by adding 1 with it.


def check_guess(guess, answer):
global score, applied_ques
if guess == answer:
print('Correct answer!')
score += 1
else:
print(f'Wrong!, The answer is: {answer}')
applied_ques += 1

Show the Score

total score

The name show_score() suggests showing the score. It shows the total score out of 10.


def show_score():
print(f'Total Score: {score}/{applied_ques}.')

The Main Function

I have divided the main function into several parts so that it can be easily understood by you.

First, open the CSV file in the read mode and declare a CSV reader variable. If you don't know how to handling files in python, read the separate article on this topic.


if __name__ == "__main__":
print('=====World Quiz=====')

with open('questions.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)

Declare a for loop to read the data from that 'csvreader' variable. Remember, at the very first of the program we declared a variable called 'line_count'. It will be used here to ignore the first row of the CSV file. Because the first row represents the column names(see in the above pic.), and we don't need those in this program.


csvreader = csv.reader(csvfile)

for row in csvreader:
if line_count == 0:
line_count += 1

The else part is for printing the question and corresponding answers choices from the CSV file. Next declare a variable named 'correct_choice' and assign 'False' value to it.


line_count += 1
else:
print(f"\n{row[0]}\nA. {row[1]} B. {row[2]} C. {row[3]} D. {row[4]}\n")
correct_choice = False

Here we will check if the player has entered the correct option or not among 'A', 'B', 'C', or 'D'. If the option is not correct then the loop will be circled until the player enters the right one. Next, increase the value of the 'line_count' variable by one.

You might be thinking about why we're making our code more complex. This is because to make our quiz game more intelligent.


correct_choice = False

while not correct_choice:
guess = input("Type A, B, C, or D\n")
if guess.upper() in ['A', 'B', 'C', 'D']:
check_guess(row[options[guess.upper()]], row[5])
correct_choice = True

line_count += 1


Remember, in the check_guess() function we increased the value of 'applied_ques' by one for every call. Now, the code will check if the player answered 10 questions or not. If YES then it will call the show_score() function and ask the player to play again or not.


line_count += 1

if applied_ques == 10:
show_score()
play_again = input('Want to play again?(Y/N): ')
if play_again in ['N', 'n']:
break
else:
line_count = 1
applied_ques = 0
score = 0

Imagine, our CSV file doesn't contain the data in the multiply of 10. Then, how our code will work perfectly? To defeat this problem we will perform an extra checking. If the applied_question is not 10 then it will show the score based on the rest of the questions and show the score.

 
score = 0
if applied_ques != 10:
show_score()

print('Thank You!')

Compact Code

Here is the full code for your convenience.


'''Quiz Game in Python'''
import csv

score = 0
line_count = 0
applied_ques = 0

# Initialize a dictionary
options = {
'A': 1,
'B': 2,
'C': 3,
'D': 4
}

def check_guess(guess, answer):
global score, applied_ques
if guess == answer:
print('Correct answer!')
score += 1
else:
print(f'Wrong!, The answer is: {answer}')
applied_ques += 1

def show_score():
print(f'Total Score: {score}/{applied_ques}.')


if __name__ == "__main__":
print('=====World Quiz=====')

with open('questions.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)

for row in csvreader:
if line_count == 0:
line_count += 1
else:
print(f"\n{row[0]}\nA. {row[1]} B. {row[2]} C. {row[3]} D. {row[4]}\n")
correct_choice = False

while not correct_choice:
guess = input("Type A, B, C, or D\n")
if guess.upper() in ['A', 'B', 'C', 'D']:
check_guess(row[options[guess.upper()]], row[5])
correct_choice = True

line_count += 1

if applied_ques == 10:
show_score()
play_again = input('Want to play again?(Y/N): ')
if play_again in ['N', 'n']:
break
else:
line_count = 1
applied_ques = 0
score = 0
if applied_ques != 10:
show_score()

print('Thank You!')

Download the zip file

The project contains one python file and a CSV file. The CSV file is must be required by the python program. I recommend You, download the zip file of this project from my GitHub page through the download button.


Output

Watch the entire video to understand how this Quiz game works.

👉Visit AlsoCreate a Time Wasting Websites Blocker using Python

Summary

In this tutorial, we build a Quiz game in Python. The questions for this quiz game were stored in a CSV file. We used that data. You can modify the CSV file by adding more questions to it.

While modifying the CSV file, one thing always keeps in mind, do not to leave any cell empty, if so, the code will not work perfectly.

That's all for this tutorial. Do enjoy this game and let me know through a reply, what you've scored for the first 10 questions.

Thanks for reading!💙

PySeek

Reference

World GK Quiz Questions and Answers 2022 - Edudwar

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post