Skip to content

Instantly share code, notes, and snippets.

@CodeByAidan
Created July 1, 2024 18:23
Show Gist options
  • Save CodeByAidan/d273433fe77fcf4602a2b9c1849e4257 to your computer and use it in GitHub Desktop.
Save CodeByAidan/d273433fe77fcf4602a2b9c1849e4257 to your computer and use it in GitHub Desktop.
just some example quiz using model inheritance with @OverRide from typing in Python 3.12
import random
from dataclasses import dataclass
from string import ascii_lowercase
from typing import override
@dataclass
class Question:
prompt: str
answer: str
def ask(self) -> bool:
answer: str = input(f"\n{self.prompt} ")
return answer == self.answer
@dataclass
class MultipleChoiceQuestion(Question):
distractors: list[str]
@override
def ask(self) -> bool:
print(f"\n{self.prompt}")
alternatives: list[str] = random.sample(
self.distractors + [self.answer], k=len(self.distractors) + 1
)
labeled_alternatives = dict(zip(ascii_lowercase, alternatives))
for label, alternative in labeled_alternatives.items():
print(f" {label}) {alternative}", end="")
answer: str = input("\n\nChoice? ")
return labeled_alternatives.get(answer) == self.answer
questions: list[Question] = [
Question("Who created Python?", "Guido van Rossum"),
MultipleChoiceQuestion(
"What's a PEP?",
"A Python Enhancement Proposal",
distractors=[
"A Pretty Exciting Policy",
"A Preciously Evolved Python",
"A Potentially Epic Prize",
],
),
]
score = 0
for question in random.sample(questions, k=len(questions)):
if question.ask():
score += 1
print("Yes, that's correct!")
else:
print(f"No, the answer is '{question.answer}'")
print(f"\nYou got {score} out of {len(questions)} correct")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment