Derive and Display Categories
Build the category list from your data using set, sorted, and join
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Before asking the player to choose a category, the quiz needs to show which categories exist. You could write a string by hand, but that string would go stale the moment you add a question in a new category. The categories are already in your data — read them from there.
set()
A set is a collection that holds each value only once — duplicates are removed automatically:
words = ["apple", "banana", "apple", "cherry", "banana"]
unique = set(words)
# {"apple", "banana", "cherry"}Ten questions share six categories, so iterating over QUESTIONS produces duplicates. Wrapping that in set() gives you each category exactly once.
sorted()
sorted() takes any collection and returns a new list in alphabetical order:
sorted({"banana", "apple", "cherry"})
# ["apple", "banana", "cherry"]Sets have no guaranteed order, so sorted() ensures the output is consistent every time.
", ".join()
join() turns a list of strings into a single string, placing the separator between each item:
items = ["apple", "banana", "cherry"]
print(", ".join(items))
# apple, banana, cherryThe string before .join() is the separator — ", " puts a comma and a space between each item.
Putting it together
categories = sorted(set(q["category"] for q in QUESTIONS))
print("Categories: " + ", ".join(categories))q["category"] for q in QUESTIONS reads every category value from QUESTIONS — ten values, with duplicates. set(...) removes the duplicates. sorted(...) alphabetizes them. ", ".join(categories) formats them as a comma-separated string for the player to read.
Instructions
Print the available categories before each round.
- At the top of the
while True:loop, before thetry/except, addcategories = sorted(set(q["category"] for q in QUESTIONS))— the inner part reads every category from QUESTIONS (with duplicates),set(...)removes duplicates, andsorted(...)alphabetizes them. - On the next line, add
print("Categories: " + ", ".join(categories))—", ".join(categories)turns the sorted list into a single comma-separated string.
QUESTIONS = [
{"text": "What is the type of the value 3.14?", "options": ["int", "str", "float", "bool"], "correct": 3, "category": "types"},
{"text": "What keyword defines a function in Python?", "options": ["for", "def", "if", "class"], "correct": 2, "category": "functions"},
{"text": "What does print() do?", "options": ["Stores a value", "Returns a number", "Displays output", "Reads input"], "correct": 3, "category": "output"},
{"text": "What type does input() always return?", "options": ["int", "float", "str", "bool"], "correct": 3, "category": "output"},
{"text": "Which keyword starts a for loop?", "options": ["loop", "repeat", "for", "each"], "correct": 3, "category": "loops"},
{"text": "What does len() return?", "options": ["The first item", "The last item", "The number of items", "The sum"], "correct": 3, "category": "basics"},
{"text": "What is the result of 10 // 3?", "options": ["3.33", "3", "1", "0"], "correct": 2, "category": "basics"},
{"text": "Which keyword exits a loop early?", "options": ["exit", "return", "stop", "break"], "correct": 4, "category": "loops"},
{"text": "What does elif stand for?", "options": ["else if", "elif loop", "end loop if", "extra loop"], "correct": 1, "category": "conditionals"},
{"text": "What does a function return with no return statement?", "options": ["0", "False", "None", "Error"], "correct": 3, "category": "functions"},
]
def ask_question(q):
print(q["text"])
print()
print(f" 1) {q['options'][0]}")
print(f" 2) {q['options'][1]}")
print(f" 3) {q['options'][2]}")
print(f" 4) {q['options'][3]}")
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 == q["correct"]
print()
print(f"You answered: {answer}")
if is_correct:
print("Correct!")
else:
print(f"Wrong! The correct answer was option {q['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 q in questions_for_round:
result = ask_question(q)
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: categories = sorted(set(q["category"] for q in QUESTIONS))
# Step 2: print("Categories: " + ", ".join(categories))
try:
num_input = input(f"How many questions? (1-{len(QUESTIONS)}, enter for all): ").strip()
if num_input:
num = int(num_input)
else:
num = len(QUESTIONS)
except ValueError:
num = len(QUESTIONS)
print()
run_quiz(num=num)
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