计算机科学 · 第 1 册 · 1–9 年级

Primary & Middle School Computer Science

本书暂未推出简体中文版。现有版本:English。

Primary & Middle School Computer Science · 1–9 年级

24Project: A Quiz Game

This chapter builds one 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. 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 takes parameters and returns a value (Chapter 19). A list keeps values in order, with indices from 0 (Chapter 20). strip and lower return a cleaned copy of a string (Chapter 21). A while loop repeats until its condition is false (Chapter 18). Bugs are found by reproducing, shrinking and changing one thing at a time (Chapter 23).

24.1 What must it do?

The paragraph above is written for people. Before writing code, turn it into a numbered list of things to check, each one small enough to test:

  1. The questions and their answers are kept in two lists 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 ends with one line in a fixed format, which another program could read.

Then plan the functions. 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.
The plan of the finished program: an arrow goes from a function to each 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 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.

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).
Two parallel lists: the same index picks a question and its answer (questions shortened here).

The check at line 16 catches a list that is one item short, before the game goes wrong. From now on, the lists live in a file of their own, questions.py, with a second pair of lists 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".

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 that returns scripted answers, then checks the points that ask returns.

24.4 The whole quiz

play walks through the two lists with one index and adds up the points.

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 asks for the level until the player types one of the two.

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.
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 of requirements: a result in a fixed format, which a person can read and a 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.

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.
The five versions, with what each one adds.

24.7 Exercises

Exercise 24.1 ★

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

Solution

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

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

Solution of Exercise 24.3.

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

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 from a list. Which list, and which line of version 1 would have warned about it?

Solution

Solution of Exercise 24.4.

An item 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

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.

Exercise 24.6 ★★

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

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

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 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 change?

Solution

Solution of Exercise 24.7.

questions.py gets two more lists, MEDIUM_QUESTIONS and MEDIUM_ANSWERS; choose_level accepts "medium" in its while condition; main gets one more elif to pick the medium lists. normalise, ask and play do not change: they work on any pair of lists.

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

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×3+1=321 + 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.

Solution

Solution of Exercise 24.9.

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 playing becomes False at quit, which ends the loop before the next question.

Exercise 24.10 ★★★

Write a 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

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:

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

Solution of Exercise 24.11.

The highest is 10, every answer right at once; the lowest is 0. With aa right first answers and bb right second answers, the score is a+b/2a + b/2 with a+b≤10a + b \le 10. Any number of halves kk from 0 to 20 can be made: if kk is even, take a=k/2a = k/2 and b=0b = 0; if kk is odd, take a=(k−1)/2a = (k-1)/2 and b=1b = 1, and then a+b≤10a + b \le 10 since k≤19k \le 19. So the 21 scores 0, 0.5, 1, …, 10 can all be reached. A program that tries every aa and bb (the 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 of lists, with every accepted answer, and change ask to match.

Solution

Solution of Exercise 24.12.

Each answer becomes a list, and in tests whether the typed answer is one of them:

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