Configurable Length
Exit

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.

  1. Change the run_quiz signature from def run_quiz(questions=QUESTIONS): to def run_quiz(questions=QUESTIONS, num=None): — the None default means the caller can omit num and still get all questions.
  2. At the top of run_quiz, add if num is None: num = len(questions) — this replaces the sentinel with the actual list length when no count was specified.
  3. Replace total = len(questions) with total = len(questions_for_round), update the for loop to iterate over questions_for_round, and change print("=== Python Quiz ===") to print(f"=== Python Quiz ({total} questions) ===") — so the round uses only the sliced subset and the player sees the count upfront.