show_results

Extract the score display and grade message into a show_results function

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

After the for loop, the quiz prints the score and a grade message — eight lines that always run together. Extract them into a function so the while loop body becomes shorter and the results logic has a single home.

Defining show_results

The function needs to know the score and total to do its job. Pass both as parameters:

def show_results(score, total):
    print(f"Score: {score}/{total}")
    if score == total:
        print("Perfect score!")
    elif score >= 2:
        print("Great job!")
    elif score >= 1:
        print("Not bad!")
    else:
        print("Keep practicing!")

Calling show_results

Replace the eight-line block in the while loop with a single call:

show_results(score, total)

The values of score and total at the time of the call become the parameters inside the function.

Default parameters preview

Python lets you set a default value for a parameter so callers can omit it:

def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Alice")           # Hello, Alice!
greet("Bob", "Hi")       # Hi, Bob!

You will use default parameters in the next chapter when you define run_quiz.

Instructions

Extract the results display into a function so the while loop body becomes shorter and the grade logic has a single home.

  1. After the ask_question function definition, define a function named show_results with parameters score and total — it needs both values to print the score line and decide which grade message to show.
  2. Inside show_results, call print(f"Score: {score}/{total}") — this shows the player how many questions they got right out of the total.
  3. Add an if/elif/elif/else chain: score == total prints "Perfect score!", score >= 2 prints "Great job!", score >= 1 prints "Not bad!", else prints "Keep practicing!" — the conditions are ordered from most restrictive to least so each score falls into exactly one branch.
  4. In the while loop, replace the eight lines from print(f"Score: ...") through print("Keep practicing!") with a single call: show_results(score, total) — one line replaces eight, and the logic now has a single home that's easy to find and change.