Call run_quiz
Replace the while loop body with a single run_quiz() call
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
run_quiz now holds everything that makes up one quiz round. The while loop still has the old expanded body — nine lines doing exactly what one call can do.
Replacing those nine lines with run_quiz() makes the loop's purpose clear at a glance:
while True:
run_quiz()
print()
again = input("Play again? (y/n): ")
if again != "y":
breakThe loop no longer describes *how* a round works — it just says run the quiz, then ask whether to play again. The details live inside run_quiz where they belong.
Instructions
Replace the while loop body with a single call to run_quiz.
- In the
while True:loop, replace everything fromscore = 0throughshow_results(score, len(QUESTIONS))with a single call:run_quiz()— one call now runs an entire quiz round, and the loop only needs to handle the play-again prompt.
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),
]
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
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!")
def run_quiz(questions=QUESTIONS):
total = len(questions)
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
show_results(score, total)
while True:
# Step 1: Replace the block below with run_quiz()
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
show_results(score, len(QUESTIONS))
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