Create a file named quiz_app.py
and add the following code:
pythonCopy codeclass Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
class Quiz:
def __init__(self, questions):
self.questions = questions
self.score = 0
def run(self):
for question in self.questions:
print(question.prompt)
user_answer = input("Your answer: ")
if user_answer.lower() == question.answer.lower():
self.score += 1
print("Correct!\n")
else:
print(f"Wrong! The correct answer was: {question.answer}\n")
self.show_score()
def show_score(self):
print(f"You scored {self.score} out of {len(self.questions)}.")
def main():
questions = [
Question("What is the capital of France?\n(a) London\n(b) Paris\n(c) Rome\n", "b"),
Question("Which planet is known as the Red Planet?\n(a) Earth\n(b) Mars\n(c) Jupiter\n", "b"),
Question("What is 2 + 2?\n(a) 3\n(b) 4\n(c) 5\n", "b"),
Question("What is the largest ocean on Earth?\n(a) Atlantic\n(b) Indian\n(c) Pacific\n", "c"),
Question("What is the chemical symbol for gold?\n(a) Au\n(b) Ag\n(c) Fe\n", "a"),
]
quiz = Quiz(questions)
quiz.run()
if __name__ == "__main__":
main()
Step 2: Running the Quiz Application
- Open your terminal (or command prompt).
- Navigate to the directory where you saved
quiz_app.py
. - Run the script using the command:bashCopy code
python quiz_app.py
How It Works
- Question Class: Represents a quiz question with a prompt and the correct answer.
- Quiz Class: Manages the list of questions and keeps track of the user’s score. It has methods to run the quiz and display the score.
- Main Function: Initializes a list of questions and starts the quiz.
Example Quiz Questions
The quiz consists of the following questions:
- What is the capital of France? (a) London (b) Paris (c) Rome
- Which planet is known as the Red Planet? (a) Earth (b) Mars (c) Jupiter
- What is 2 + 2? (a) 3 (b) 4 (c) 5
- What is the largest ocean on Earth? (a) Atlantic (b) Indian (c) Pacific
- What is the chemical symbol for gold? (a) Au (b) Ag (c) Fe
Leave a Reply