Code a quiz game with Python on Raspberry Pi

By Lucy Hattersley. Posted

Make your own text quiz game that mangles famous phrases using the Python language

Many people progress from Scratch to Python, a programming language that is powerful, easy to get started with, and much easier to read and write than other languages.
We’re going to make a simple quiz question generator that strips the vowels and shuffles the spaces in a phrase. The player has to work out what that phrase is.

We’ll be using Thonny, which provides a friendly single-screen environment for running and testing Python code. Like Scratch, the Thonny IDE (integrated development environment) comes pre-installed in the Raspbian with Desktop and Recommended Software operating system.

This feature was written by Sean McManus and first appeared in The MagPi issue 82. Get a free Raspberry Pi computer with a 12-month subscription to The MagPi magazine.

See also: The best Python websites and resources, Create a Python game: how to make a puzzle game called Same, Functions: Learn code with Python and Raspberry Pi

Code a Quiz Game in Python: What you'll need

First create a list of questions

As well as variables, Python has lists, which can store multiple pieces of information. Our program creates a list called questions. Each item in the list is a piece of text, known as a string. In Python, strings are surrounded by double quotes to show where they start and end. The whole list is enclosed in square brackets, and there are commas between the list items. Type in the code below, save your program, and then click Run. If it worked, you should see no error messages in the Shell window.

import random

questions = ["As You Like It", 
    "The Tempest", "Measure for Measure",
    "Much Ado About Nothing", 
    "The Comedy of Errors",
    "King Lear", "Cymbeline", 
    "Hamlet", "Coriolanus", "Othello",
    "Love's Labour's Lost", 
    "King John", "Julius Caesar", 
    "Edward III"]

Getting Python indentation right

Python uses indentation to show which instructions belong to a function, an if statement, or a repeating section. You can have multiple levels of indentation. The last line belongs to the if instruction, and that is repeated inside the for loop. The best way to get the indentation right is to remember the colon at the end of the previous line. Then, Thonny will add the indentation for you automatically. If you forget, use four spaces at the start of the line to insert the indentation. You’ll still need to fix that missing colon, though!

Pick a random question

Python includes modules of prewritten code you can use, such as the random module we imported. The first new instruction creates a new variable called chosenphrase and puts a randomly chosen question into it. The second line converts the chosenphrase to upper case. Run the program a few times and look at the value of chosen_phrase in the Variables pane. You should see different names come up, although names can also repeat.

Add a line of space and add the following code:

chosen_phrase = random.choice(questions)
chosen_phrase = chosen_phrase.upper()

Strip the vowels and spaces

Let’s create a new list of forbidden characters, chiefly the vowels, but also the space and the apostrophe. That last list item in the vowels list is an apostrophe inside double quotes. We create an empty string variable, called puzzle. We’re going to go through each letter in the phrase, check whether it’s in the vowels list, and if not, add it to the end of the puzzle string. The for instruction sets up a repeating piece of code, called a loop. The instructions that should be repeated are indented from left. Each time around the loop, the variable letter is set to contain the next character from the chosen_phrase string. The if instruction checks whether the letter is in the vowels list. If it is not, the letter is added to the end of puzzle. The += means ‘add at the end’. Run the program, then test it’s working by looking at the contents of puzzle in the Variables panel. It should contain no vowels, spaces, or apostrophes.

Add the following code to the program:

vowels = ["A", "E", "I", "O", "U", " ", "'"]
puzzle = ""

for letter in chosen_phrase:
    if not letter in vowels:
        puzzle += letter

Insert random spaces

Each character in the string can be referred to by its position number, starting at 0. The number is called an index, and you put it in square brackets after the string. Try this in the Shell (click on the line starting with ‘>>>’). Instructions in the Shell are carried out immediately. Enter the following:

print("Hello"[1])

You get ‘e’ back (because the first character is number 0). You can get a chunk too (called a slice) by giving a start and end index, like this:

print("Hello"[1:4])

It gives you ‘ell’ because the last index position (4) is left out. We’ll create a new list, called puzzlewithspaces, by adding chunks of the puzzle string and a space until there’s no puzzle string left. The while loop repeats the indented instructions below as long as the length of puzzle is more than 0. The grouplength variable is given a random whole number (integer) from 1 to 5. Then that many letters are added to puzzlewith_spaces from the front of puzzle, plus a space. Those characters are then cut off the front of puzzle. The slicing here only uses one number, so the other one is assumed to be the start or end of the string.

Add this code to your program:

puzzle_with_spaces = ""

while len(puzzle) > 0:
    group_length = random.randint(1,5)
    puzzle_with_spaces += 
puzzle[:group_length] + " "
    puzzle = puzzle[group_length:]

Add collision detection

It prints the puzzlewithspaces. It then uses the input() function to ask you what your guess is. Your answer goes into the guess variable, and is then converted to upper case to make sure it matches the correct answer if it’s right. The if instruction checks whether guess is the same as chosen_phrase. If so, it prints one message. Otherwise, the instruction indented under else runs, to tell you the right answer. In Python, one = is used to put a value into a variable, but two (==) are used to compare items in an if instruction.

Add this code to the end of the program:

print(puzzle_with_spaces)
guess = input("What is your guess? ")
guess = guess.upper()

if guess == chosen_phrase:
    print("That's correct!")
else:
    print("No. The answer is ", chosen_phrase)

Click the Run button and hopefully you’ll see some letters in the Shell and ‘What is your guess?’ Enter an answer and you’ll see ‘That’s correct!’ or ‘No. The answer is’ and the correct response.
If you’ve typed the code out by hand, it’s likely that you’ll see an error message. Go through your code line-by-line and compare it to the full code in quiz_game.py.

Click here to get the quiz_game.py code from our GitHub.

import random

questions = ["As You Like It", "The Tempest", 
"Measure for Measure", "Much Ado About Nothing", 
"The Comedy of Errors", "King Lear", "Cymbeline",
"Hamlet", "Coriolanus", "Othello","Love's Labour's Lost", "King John", "Julius Caesar", "Edward III"]

chosen_phrase = random.choice(questions)
chosen_phrase = chosen_phrase.upper()

vowels = ["A", "E", "I", "O", "U", " ", "'"]
puzzle = ""


for letter in chosen_phrase:
    if not letter in vowels:
        puzzle += letter


puzzle_with_spaces = ""


while len(puzzle) > 0:
    group_length = random.randint(1,5)
    puzzle_with_spaces += puzzle[:group_length] + " "
    puzzle = puzzle[group_length:]


print(puzzle_with_spaces)
guess = input("What is your guess? ")
guess = guess.upper()


if guess == chosen_phrase:
    print("That's correct!")
else:
    print("No. The answer is ", chosen_phrase)

 

More articles from The MagPi magazine

Subscribe