No title

ESWAP GHANA
0
import random class Quiz: def __init__(self, questions): self.questions = questions self.score = 0 def display_question(self, question_num): question = self.questions[question_num]['question'] options = self.questions[question_num]['options'] print(f"\nQuestion {question_num + 1}: {question}") for i, option in enumerate(options, start=1): print(f"{i}. {option}") def get_user_input(self): while True: try: user_input = int(input("\nEnter your answer (1-4): ")) if 1 <= user_input <= 4: return user_input else: print("Invalid input. Please enter a number between 1 and 4.") except ValueError: print("Invalid input. Please enter a number.") def check_answer(self, question_num, user_answer): correct_answer = self.questions[question_num]['correct'] if user_answer == correct_answer: print("\033[92mCorrect!\033[0m") self.score += 1 else: print("\033[91mWrong!\033[0m") print(f"The correct answer is: {correct_answer + 1}. {self.questions[question_num]['options'][correct_answer]}") def run_quiz(self): random.shuffle(self.questions) for i in range(len(self.questions)): self.display_question(i) user_answer = self.get_user_input() self.check_answer(i, user_answer) print(f"\nQuiz completed! Your score: {self.score}/{len(self.questions)}") # Example usage: questions_data = [ { 'question': 'What is the capital of France?', 'options': ['Berlin', 'Madrid', 'Paris', 'Rome'], 'correct': 2 }, { 'question': 'Which programming language is this quiz written in?', 'options': ['Python', 'Java', 'C++', 'JavaScript'], 'correct': 0 }, { 'question': 'What is the largest mammal?', 'options': ['Elephant', 'Blue Whale', 'Giraffe', 'Hippopotamus'], 'correct': 1 } ] quiz = Quiz(questions_data) quiz.run_quiz()

Post a Comment

0Comments

Post a Comment (0)