Python Trivia Game
In this tutorial, we'll create a simple command line interface (CLI) program that runs a quick game of trivia.
Making Questions
For our trivia game, we'll need to make some questions and store them for our program mto access. We'll have them in this format:
questions = [{"question" : "Who created Python?", "possible" : ["Guido Van Rossum", "James Gosling", "Donald Knuth", "Dennis Ritchie"], "correct" : "Guido Van Rossum"}, {"question" : "What is the oldest American university?", "possible" : ["Harvard University", "Yale University", "College of William and Mary", "Massachusetts Institute of Technology"], "correct" : "Harvard University"}]
Notice how the questions
variable is a list of dictionaries, which contain the question name, possible answers, and correct answer.
We will then put this in a Python file called questions.py
so we can more easily access it. So, whenever we need to access the questions, we can simply type import questions
and use it as questions.questions
.
Making the App
Now, it's time to make our app, which will run in the command line. First of all, we need to import the things we need:
import questions
import random
We will be using the random
module to randomize the questions and answers.
Then, we wrap the rest of our code to ask the player a question in a giant while True
loop, so that our app will ask the player a question one after another:
while True:
Now, inside the loop, we use the random.choice()
function to choose a random question from our list of random questions and print the name of the question:
current_question = random.choice(questions.questions)
print(current_question['question'])
We then use the random.shuffle()
function to randomly reorganize the list of answers. We also declare a variable called answers
so we don't have to repeat ourselves:
random.shuffle(current_question['answers'])
answers = current_question['answers']
We then print out each of the questions in numerical order:
for answer in range(len(answers)):
print(f"{answer+1}. {answers[answer]}")
Then, we ask the player to enter their answer. We wrap it in a try-except block so that when the player enters something that's not a number, we print an error and exit the game:
try:
selected_answer = int(input("Enter your answer: "))
except ValueError:
print("Error: invalid number")
break
After that, we check if the answer that the user gave was correct. Remember that we increased all the list indices when we were listing the answers, so we now have to decrease the answer by one. We wrap it in a try-except block so that whenever the player chooses an answer that wasn't listed, the program prints an error and exits:
try:
if answers[selected_answer - 1] == current_question['correct']:
print("You answered correctly!")
else:
print("Your answer wasn't correct. (womp womp)")
except IndexError:
print("Error: invalid answer")
break
Finally, we can run our code. Try a few different test cases and see if it works!
You can find the full code for the tutorial here.
Extensions
Fun extension ideas:
- Add more questions
- Use a JSON file for the data instead
- Add the ability to create questions
- Allow points for each question the player gets correct
- Allow the player to have a quiz session with a set amount of questions
- Make the program into a web app (using something like Flask)