Quiz Application

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

  1. Open your terminal (or command prompt).
  2. Navigate to the directory where you saved quiz_app.py.
  3. Run the script using the command:bashCopy codepython 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:

  1. What is the capital of France? (a) London (b) Paris (c) Rome
  2. Which planet is known as the Red Planet? (a) Earth (b) Mars (c) Jupiter
  3. What is 2 + 2? (a) 3 (b) 4 (c) 5
  4. What is the largest ocean on Earth? (a) Atlantic (b) Indian (c) Pacific
  5. What is the chemical symbol for gold? (a) Au (b) Ag (c) Fe

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *