python选择题代码设计
时间: 2023-07-23 11:03:38 浏览: 157
以下是一个简单的 Python 选择题代码设计:
```python
# 问题类
class Question:
def __init__(self, text, choices, correct_answer):
self.text = text
self.choices = choices
self.correct_answer = correct_answer
def check_answer(self, answer):
return answer.lower() == self.correct_answer.lower()
# 测验类
class Quiz:
def __init__(self, questions):
self.questions = questions
self.score = 0
self.current_question_index = 0
def get_question(self):
return self.questions[self.current_question_index]
def display_question(self):
question = self.get_question()
print(question.text)
for choice in question.choices:
print("- " + choice)
def next_question(self):
self.current_question_index += 1
def check_answer(self, answer):
question = self.get_question()
if question.check_answer(answer):
self.score += 1
print("Correct!")
else:
print("Incorrect!")
self.next_question()
def complete(self):
print("Your score is", self.score, "out of", len(self.questions))
# 创建问题
q1 = Question("What is the capital of France?", ["London", "Paris", "Madrid", "Berlin"], "Paris")
q2 = Question("What is the largest country in the world?", ["Russia", "Canada", "China", "USA"], "Russia")
q3 = Question("What is the currency of Japan?", ["Yen", "Dollar", "Euro", "Pound"], "Yen")
# 创建测验
quiz = Quiz([q1, q2, q3])
# 显示问题并获取答案
while quiz.current_question_index < len(quiz.questions):
quiz.display_question()
answer = input("Enter your answer: ")
quiz.check_answer(answer)
# 完成测验并显示得分
quiz.complete()
```
此代码实现了一个简单的选择题测验,包括问题类和测验类。问题类包含问题文本、选项和正确答案,测验类包含问题列表、得分和当前问题索引。测验类还包含显示问题、获取答案、检查答案和完成测验的方法。最后,通过循环显示每个问题,获取用户输入的答案,并检查答案是否正确。在完成所有问题后,测验类显示用户的得分。