Configurable Length
Add a num parameter to run_quiz so players can choose how many questions to answer
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Ten questions is a longer round than three. Sometimes a player wants a quick five-question warmup, other times they want the full set. A num parameter makes the round length configurable without changing anything else.
Slicing
A slice takes the first num items from the list without modifying the original:
questions_for_round = questions[:num]questions[:5] returns the first five questions. questions[:len(questions)] returns all of them.
None as a sentinel
num=None signals "not specified." The function checks for it and replaces it with len(questions):
def run_quiz(questions=QUESTIONS, num=None):
if num is None:
num = len(questions)Calling run_quiz() with no arguments still works — it runs all questions.
Instructions
Add a num parameter to run_quiz and use slicing to limit the round.
- Change the
run_quizsignature fromdef run_quiz(questions=QUESTIONS):todef run_quiz(questions=QUESTIONS, num=None):— theNonedefault means the caller can omitnumand still get all questions. - At the top of
run_quiz, addif num is None: num = len(questions)— this replaces the sentinel with the actual list length when no count was specified. - Replace
total = len(questions)withtotal = len(questions_for_round), update theforloop to iterate overquestions_for_round, and changeprint("=== Python Quiz ===")toprint(f"=== Python Quiz ({total} questions) ===")— so the round uses only the sliced subset and the player sees the count upfront.
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!")
# Step 1: Add num=None parameter to run_quiz
def run_quiz(questions=QUESTIONS):
# Step 2: Add num check here
total = len(questions)
score = 0
streak = 0
print("=== Python Quiz ===") # Step 4: show total in header
print()
# Step 3: Add questions_for_round = questions[:num]
# Step 4: Update total and for loop to use questions_for_round
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:
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