Choose How Many
Ask the player how many questions to answer before each round
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
run_quiz now accepts a num argument, but the while loop still calls run_quiz() with no arguments — always running all ten questions. Asking the player before each round puts them in control.
You already know try/except from the answer-validation loop in ask_question. The same pattern works here: try to convert the input to an integer; if it fails, fall back to all questions.
Pressing Enter without typing anything produces an empty string. Calling int("") raises a ValueError — so you need to check for an empty string before converting, or handle it in the except block.
Instructions
Ask the player how many questions they want before each round.
- In the
while True:loop, before therun_quiz()call, add atry/except ValueErrorblock — insidetry, read input withinput(f"How many questions? (1-{len(QUESTIONS)}, enter for all): ")and strip whitespace with.strip(); if the result is an empty string, setnum = len(QUESTIONS); otherwise convert it withint()and assign tonum— the try/except catches non-numeric input and falls back to all questions. - Replace
run_quiz()withrun_quiz(num=num)— this passes the player's choice to the function. - Add
print()after thetry/exceptblock (beforerun_quiz) — this adds a blank line between the prompt and the quiz header.
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),
("What type does input() always return?", "int", "float", "str", "bool", 3),
("Which keyword starts a for loop?", "loop", "repeat", "for", "each", 3),
("What does len() return?", "The first item", "The last item", "The number of items", "The Sum", 3),
("What is the result of 10 // 3?", "3.33", "3", "1", "0", 2),
("Which keyword exits a loop early?", "exit", "return", "stop", "break", 4),
("What does elif stand for?", "else if", "elif loop", "end loop if", "extra loop", 1),
("What does a function return with no return statement?", "0", "False", "None", "Error", 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()
while True:
answer_text = input("Your answer (1-4): ")
try:
answer = int(answer_text)
except ValueError:
print("Please enter 1, 2, 3, or 4.")
continue
if answer < 1 or answer > 4:
print("Please enter 1, 2, 3, or 4.")
continue
break
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, num=None):
if num is None:
num = len(questions)
score = 0
streak = 0
questions_for_round = questions[:num]
total = len(questions_for_round)
print(f"=== Python Quiz ({total} questions) ===")
print()
for text, o1, o2, o3, o4, correct in questions_for_round:
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: ask how many questions (try/except, empty string check)
# Step 3: print blank line
# Step 2: replace run_quiz() with run_quiz(num=num)
run_quiz()
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