---
title: "Project: A Quiz Game"
book: "Primary & Middle School Computer Science"
subject: computer-science
language: en
chapter: 24
exercises: 12
source: https://one-course.com/books/computer-science/1/en/chapter/24-project-a-quiz-game
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 24 — Project: A Quiz Game

This chapter builds one [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) from start to finish, a quiz game, in five versions. Each version runs, each is tested, and each adds one thing to the one before. Here is what the finished game must do:

> A quiz asks ten questions, read from [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list). The player may type an answer in capitals or small letters, with extra spaces around it. A right answer gives one point; after a wrong one the player has a second chance, worth half a point. The score is shown at the end. The quiz has an easy level and a hard level.

**You already know.**

A [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) takes [parameters](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-parameter) and returns a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) ([Chapter 19](https://one-course.com/books/computer-science/1/en/chapter/19-functions#ch-g7-functions)). A [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) keeps [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) in order, with indices from 0 ([Chapter 20](https://one-course.com/books/computer-science/1/en/chapter/20-lists#ch-g7-lists)). `strip` and `lower` return a cleaned copy of a [string](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string) ([Chapter 21](https://one-course.com/books/computer-science/1/en/chapter/21-strings#ch-g7-strings)). A `while` [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) repeats until its [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) is false ([Chapter 18](https://one-course.com/books/computer-science/1/en/chapter/18-repeating-with-while#ch-g6-while-loops)). [Bugs](https://one-course.com/books/computer-science/1/en/chapter/23-finding-and-fixing-bugs#def-g7-finding-and-fixing-bugs-bug) are found by reproducing, shrinking and changing one thing at a time ([Chapter 23](https://one-course.com/books/computer-science/1/en/chapter/23-finding-and-fixing-bugs#ch-g7-finding-and-fixing-bugs)).

## 24.1 What must it do?

The paragraph above is written for people. Before writing code, turn it into a numbered [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of things to check, each one small enough to test:

1. The questions and their answers are kept in two [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of the same length.
2. An answer is accepted whatever its capitals and its spaces at the ends.
3. A right first answer gives 1 point, a right second answer gives 0.5, a wrong second answer gives 0.
4. Every question is asked once, in order, and the score is printed at the end.
5. The player chooses the easy or the hard level, and is asked again if the level typed is neither.
6. The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) ends with one line in a fixed format, which another [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) could read.

Then plan the [functions](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function). Each one does one job and can be tested alone: `normalise` cleans a typed answer, `ask` asks one question, `play` asks them all, `choose_level` asks for the level, and `main` puts them together.

![The plan of the finished program: an arrow goes from a function to each function it calls. input is Python’s own.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-project-quiz-game/fig-3fd93b4afcc7.svg)

*The plan of the finished [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program): an arrow goes from a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) to each [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) it calls. `input` is Python’s own.*

## 24.2 Questions in lists

The first version only holds the questions and the answers, in two [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) that go together: `answers[i]` is the answer to `questions[i]`. Answers are written in small letters, so that they can be compared with what the player types, once cleaned.

```python
questions = [
    "What is the capital of France?",
    "How many legs does a spider have?",
    "What is 7 x 8?",
    "Which planet is the largest?",
    "What do bees make?",
    "How many minutes are in an hour?",
    "What is the opposite of hot?",
    "How many sides does a hexagon have?",
    "Which colour do blue and yellow make?",
    "What is 100 - 37?",
]
answers = ["paris", "8", "56", "jupiter", "honey",
           "60", "cold", "6", "green", "63"]

if len(questions) != len(answers):
    print("Error:", len(questions), "questions but", len(answers), "answers")
for i in range(len(questions)):
    print(i + 1, questions[i], "->", answers[i])
```

***Listing 24.1.** Version 1: the questions and their answers. code/grade-7/06-project-quiz-game/listings/quiz_v1.py*

```
$ python quiz_v1.py
1 What is the capital of France? -> paris
2 How many legs does a spider have? -> 8
3 What is 7 x 8? -> 56
4 Which planet is the largest? -> jupiter
9 Which colour do blue and yellow make? -> green
10 What is 100 - 37? -> 63
```

***Output 24.1.** The first four pairs and the last one. Some lines are left out.*

![Two parallel lists: the same index picks a question and its answer (questions shortened here).](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-project-quiz-game/fig-25e2efb6d4e4.svg)

*Two parallel [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list): the same [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) picks a question and its answer (questions shortened here).*

The check at line 16 catches a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) that is one [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) short, before the game goes wrong. From now on, the [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) live in a [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) of their own, `questions.py`, with a second pair of [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) for the hard level; the next versions import them.

## 24.3 Asking one question

The player may type `Paris`, `PARIS` or `" paris "`. `normalise` removes the spaces at the ends and puts the letters in small type, so that all of these become `"paris"`.

```python
def normalise(text):
    """The typed answer without spaces at the ends, in small letters."""
    return text.strip().lower()


def ask(question, answer):
    """Ask one question; return 1 point for a right answer, 0 otherwise."""
    typed = input(question + " ")
    if normalise(typed) == answer:
        print("Right!")
        return 1
    print("The answer was", answer + ".")
    return 0


if __name__ == "__main__":
    points = ask("What is the capital of France?", "paris")
    print("points:", points)
```

***Listing 24.2.** Version 2: asking one question. code/grade-7/06-project-quiz-game/listings/quiz_v2.py*

```
$ python quiz_v2.py
What is the capital of France?   PARIS 
Right!
points: 1
```

***Output 24.2.** An answer in capitals, with spaces, is accepted.*

A test of the chapter calls `ask` without a keyboard: it replaces `input` with a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) that returns scripted answers, then checks the points that `ask` returns.

## 24.4 The whole quiz

`play` walks through the two [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) with one [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) and adds up the points.

```python
from questions import EASY_ANSWERS, EASY_QUESTIONS
from quiz_v2 import ask


def play(questions, answers):
    """Ask every question in order; return the score."""
    score = 0
    for i in range(len(questions)):
        score = score + ask(questions[i], answers[i])
    return score


if __name__ == "__main__":
    score = play(EASY_QUESTIONS, EASY_ANSWERS)
    print("Your score:", score, "out of", len(EASY_QUESTIONS))
    if score == len(EASY_QUESTIONS):
        print("A perfect game!")
```

***Listing 24.3.** Version 3: the whole quiz. code/grade-7/06-project-quiz-game/listings/quiz_v3.py*

```
$ python quiz_v3.py
What is the capital of France? Paris
Right!
How many legs does a spider have? 8
Right!
What is 100 - 37? 63
Right!
Your score: 10 out of 10
A perfect game!
```

***Output 24.3.** A perfect game. Some lines are left out.*

`quiz_v3_poor.py` imports `play` and plays the same quiz with poorer answers:

```
$ python quiz_v3_poor.py
What is the capital of France? London
The answer was paris.
How many legs does a spider have? 6
The answer was 8.
What is 100 - 37? 73
The answer was 63.
Your score: 3 out of 10
```

***Output 24.4.** A poorer game: 3 out of 10. Some lines are left out.*

## 24.5 Second chances and levels

A wrong first answer now gets a second try. `ask` returns 1, 0.5 or 0, so the score starts at `0.0` and is a decimal number. A second [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) asks for the level until the player types one of the two.

```python
from questions import EASY_ANSWERS, EASY_QUESTIONS, HARD_ANSWERS, HARD_QUESTIONS
from quiz_v2 import normalise


def ask(question, answer):
    """1 point for a right first answer, 0.5 for a right second one, else 0."""
    if normalise(input(question + " ")) == answer:
        print("Right!")
        return 1
    if normalise(input("Not quite. Try again: ")) == answer:
        print("Right, half a point.")
        return 0.5
    print("The answer was", answer + ".")
    return 0


def play(questions, answers):
    score = 0.0
    for i in range(len(questions)):
        score = score + ask(questions[i], answers[i])
    return score


def choose_level():
    """Return the level the player types: "easy" or "hard"."""
    level = normalise(input("Level (easy or hard)? "))
    while level != "easy" and level != "hard":
        level = normalise(input("Please type easy or hard: "))
    return level


if __name__ == "__main__":
    if choose_level() == "easy":
        questions = EASY_QUESTIONS
        answers = EASY_ANSWERS
    else:
        questions = HARD_QUESTIONS
        answers = HARD_ANSWERS
    score = play(questions, answers)
    print("Your score:", score, "out of", len(questions))
```

***Listing 24.4.** Version 4: second chances and two levels. code/grade-7/06-project-quiz-game/listings/quiz_v4.py*

```
$ python quiz_v4.py
Level (easy or hard)? medium
Please type easy or hard: Hard
What is the capital of Australia? canberra
Right!
How many bits are in a byte? 8
Right!
What is 2 to the power 10? 1000
Not quite. Try again: 1024
Right, half a point.
How many sides does a dodecagon have? 12
Right!
What is the next prime number after 31? 37
Right!
Your score: 8.5 out of 10
```

***Output 24.5.** A hard game with a mistyped level and three second chances; two of them are among the lines left out. Some lines are left out.*

![One turn of the game, as ask plays it in version 4.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-project-quiz-game/fig-353f0026be3f.svg)

*One turn of the game, as `ask` plays it in version 4.*

## 24.6 Improving it

The last version adds the final line of the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of requirements: a result in a fixed format, which a person can read and a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) can split into its parts. Shuffling the order of the questions would make the game better, but it needs random numbers, which come in grade 9.

```python
from questions import EASY_ANSWERS, EASY_QUESTIONS, HARD_ANSWERS, HARD_QUESTIONS
from quiz_v4 import choose_level, play


def result_line(level, score, total):
    """One line in a fixed format, easy to read for a person or a program."""
    return "RESULT level=" + level + " score=" + str(score) + "/" + str(total)


def main():
    level = choose_level()
    if level == "easy":
        questions = EASY_QUESTIONS
        answers = EASY_ANSWERS
    else:
        questions = HARD_QUESTIONS
        answers = HARD_ANSWERS
    score = play(questions, answers)
    print(result_line(level, score, len(questions)))


if __name__ == "__main__":
    main()
```

***Listing 24.5.** Version 5: the finished game. code/grade-7/06-project-quiz-game/listings/quiz_v5.py*

```
$ python quiz_v5.py
Level (easy or hard)? easy
What is the capital of France? paris
Right!
How many legs does a spider have? eight
Not quite. Try again: 8
Right, half a point.
What is the opposite of hot? warm
Not quite. Try again: freezing
The answer was cold.
How many sides does a hexagon have? 6
Right!
Which colour do blue and yellow make? green
Right!
What is 100 - 37? 63
Right!
RESULT level=easy score=8.0/10
```

***Output 24.6.** An easy game, scored 8.0 out of 10. Some lines are left out.*

![The five versions, with what each one adds.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-project-quiz-game/fig-881482f90357.svg)

*The five versions, with what each one adds.*

## 24.7 Exercises

**Exercise 24.1 ★.**

What does `normalise(" Paris ")` return? And `normalise("NEW YORK")`?

**Solution of Exercise 24.1.**

`"paris"` and `"new york"`: the space inside stays, only the spaces at the ends go.

**Exercise 24.2 ★.**

In version 3, a player types `Paris`, `eight`, `56`, `jupiter`, `" Honey "`, `60`, `hot`, `6`, `green` and `63`. What score is printed?

**Solution of Exercise 24.2.**

`eight` is not `8`, and `hot` is wrong; the other eight answers are right once normalised, `" Honey "` included: `Your score: 8 out of 10`.

**Exercise 24.3 ★.**

Change `ask` of version 4 so that typing `skip` moves on at once, with 0 points and no second chance.

**Solution of Exercise 24.3.**

The typed answer is normalised once, and tested for `skip` first:

```python
def ask(question, answer):
    """Like quiz_v4's ask, but "skip" moves on at once with 0 points."""
    typed = normalise(input(question + " "))
    if typed == "skip":
        print("Skipped.")
        return 0
    if typed == answer:
        print("Right!")
        return 1
    if normalise(input("Not quite. Try again: ")) == answer:
        print("Right, half a point.")
        return 0.5
    print("The answer was", answer + ".")
    return 0
```

*Skipping a question. code/grade-7/06-project-quiz-game/exercises/skip.py*

**Exercise 24.4 ★.**

After an edit, the quiz says that every answer from question 5 on is wrong, and stops with an `IndexError` at question 10. Someone deleted one [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) from a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list). Which [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), and which line of version 1 would have warned about it?

**Solution of Exercise 24.4.**

An [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of `answers` was deleted after the fourth: from question 5 on, each question is compared with the answer to the next one, and the tenth question has no answer at all, so `answers[9]` is past the end. The check `if len(questions) != len(answers):` of version 1 would have printed `Error: 10 questions but 9 answers`.

**Exercise 24.5 ★★.**

Make version 5 print the score as a percentage as well.

**Solution of Exercise 24.5.**

In `main`, after the result line: `print(round(score / len(questions) * 100), "%")`, which prints `80 %` for the game of [Output 24.6](#out-g7-project-quiz-game-v5).

**Exercise 24.6 ★★.**

This `ask` gives 1.5 points for `paris` typed twice. Why? Fix it.

```python
def ask(question, answer):
    points = 0
    if normalise(input(question + " ")) == answer:
        points = 1
    if normalise(input("Try again: ")) == answer:
        points = points + 0.5
    return points
```

***Listing 24.6.** Too many points. code/grade-7/06-project-quiz-game/exercises/ask_bug.py*

**Solution of Exercise 24.6.**

The second question is asked even after a right first answer, and its half point is added to the 1. The [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) must return as soon as the first answer is right, as `ask` of version 4 does with its first `return 1`.

**Exercise 24.7 ★★.**

Add a third level, `medium`. Which parts of the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) change?

**Solution of Exercise 24.7.**

`questions.py` gets two more [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), `MEDIUM_QUESTIONS` and `MEDIUM_ANSWERS`; `choose_level` accepts `"medium"` in its `while` [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition); `main` gets one more `elif` to pick the medium [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list). `normalise`, `ask` and `play` do not change: they work on any pair of [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list).

**Exercise 24.8 ★★.**

How many lines does a game of version 5 show on the screen at most, when the player types a valid level at once? Why is there no maximum otherwise?

**Solution of Exercise 24.8.**

One line for the level, at most three per question (the question, the second try, the answer shown), and the result line: $1 + 10 \times 3 + 1 = 32$. A test of the chapter plays a game with every answer wrong and counts 32. A player who keeps typing a wrong level is asked again and again, one more line each time, without end.

**Exercise 24.9 ★★.**

Write a `play` that stops early when the player types `quit`, and returns the score so far. Use a `while` [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop).

**Solution of Exercise 24.9.**

```python
def play(questions, answers):
    """Ask the questions in order until they run out or the player types quit."""
    score = 0
    i = 0
    playing = True
    while playing and i < len(questions):
        typed = normalise(input(questions[i] + " "))
        if typed == "quit":
            playing = False
        elif typed == answers[i]:
            score = score + 1
        i = i + 1
    return score
```

*Stopping early. code/grade-7/06-project-quiz-game/exercises/quit.py*

The [variable](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) `playing` becomes `False` at `quit`, which ends the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) before the next question.

**Exercise 24.10 ★★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `longest_streak(points)` that takes the points of each question, such as `[1, 0.5, 1, 1, 1, 0, 1, 1, 0.5, 1]`, and returns the longest run of right first answers.

**Solution of Exercise 24.10.**

A running count of right first answers, set back to 0 by any other result, and the best count so far:

```python
def longest_streak(points):
    """The longest run of right first answers (1 point each) in a list of points."""
    best = 0
    run = 0
    for p in points:
        if p == 1:
            run = run + 1
            if run > best:
                best = run
        else:
            run = 0
    return best


print(longest_streak([1, 0.5, 1, 1, 1, 0, 1, 1, 0.5, 1]))
```

*The longest streak. code/grade-7/06-project-quiz-game/exercises/streak.py*

It prints 3, for questions 3 to 5.

**Exercise 24.11 ★★★.**

What are the highest and the lowest possible scores in a game of ten questions? Can every score in between, in steps of 0.5, be reached? How many different scores are there?

**Solution of Exercise 24.11.**

The highest is 10, every answer right at once; the lowest is 0. With $a$ right first answers and $b$ right second answers, the score is $a + b/2$ with $a + b \le 10$. Any number of halves $k$ from 0 to 20 can be made: if $k$ is even, take $a = k/2$ and $b = 0$; if $k$ is odd, take $a = (k-1)/2$ and $b = 1$, and then $a + b \le 10$ since $k \le 19$. So the 21 scores 0, 0.5, 1, …, 10 can all be reached. A [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that tries every $a$ and $b$ (the [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) `exercises/scores.py`) finds the same 21.

**Exercise 24.12 ★★★.**

A spider has `8` legs, but a player who types `eight` is right too. Change the answers into a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), with every accepted answer, and change `ask` to match.

**Solution of Exercise 24.12.**

Each answer becomes a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), and `in` tests whether the typed answer is one of them:

```python
QUESTIONS = [
    "How many legs does a spider have?",
    "Which colour do blue and yellow make?",
]
ANSWERS = [["8", "eight"], ["green"]]


def ask(question, accepted):
    """1 point when the typed answer is any of the accepted ones."""
    if normalise(input(question + " ")) in accepted:
        print("Right!")
        return 1
    print("The answer was", accepted[0] + ".")
    return 0
```

*Several accepted answers. code/grade-7/06-project-quiz-game/exercises/many_answers.py*
