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.
- After the
ask_questionfunction definition, define a function namedshow_resultswith parametersscoreandtotal— it needs both values to print the score line and decide which grade message to show. - Inside
show_results, callprint(f"Score: {score}/{total}")— this shows the player how many questions they got right out of the total. - Add an
if/elif/elif/elsechain:score == totalprints"Perfect score!",score >= 2prints"Great job!",score >= 1prints"Not bad!",elseprints"Keep practicing!"— the conditions are ordered from most restrictive to least so each score falls into exactly one branch. - In the
whileloop, replace the eight lines fromprint(f"Score: ...")throughprint("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.
QUESTIONS = [
("What is the type of the value 3.14?", "int", "str", "float", "bool", 3),
("What keyword defines a function in Python?", "for", "def", "if", "class", 2),
("What does print() do?", "Stores a value", "Returns a number", "Displays output", "Reads input", 3),
]
total = 3
def ask_question(text, o1, o2, o3, o4, correct):
print(text)
print()
print(f" 1) {o1}")
print(f" 2) {o2}")
print(f" 3) {o3}")
print(f" 4) {o4}")
print()
answer_text = input("Your answer (1-4): ")
answer = int(answer_text)
is_correct = answer == correct
print()
print(f"You answered: {answer}")
if is_correct:
print("Correct!")
else:
print(f"Wrong! The correct answer was option {correct}.")
return is_correct
# Step 1: Define show_results(score, total):
# Step 2: print(f"Score: {score}/{total}")
# Step 3: if/elif/elif/else chain for grade message
while True:
score = 0
streak = 0
print("=== Python Quiz ===")
print()
for text, o1, o2, o3, o4, correct in QUESTIONS:
result = ask_question(text, o1, o2, o3, o4, correct)
if result:
score = score + 1
streak = streak + 1
if streak >= 3:
print(f" Hot streak! ({streak} in a row)")
else:
streak = 0
# Step 4: Replace the 8 lines below with 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!")
print()
again = input("Play again? (y/n): ")
if again != "y":
break
print("Thanks for playing!")
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding