1 回答

TA貢獻(xiàn)1808條經(jīng)驗(yàn) 獲得超4個(gè)贊
下面是定義“問(wèn)題”的自定義類的示例 - 然后您可以創(chuàng)建其中的許多問(wèn)題,并以這種方式重用大量代碼。
class Question:
def __init__(self, number, question, choices, correct, chances=3):
self.number = number
self.question = question
self.choices = choices
self.correct = correct
self.chances = chances
def print(self):
print(self.question, '\n', '\n'.join(self.choices))
def guess(self):
while self.chances:
answer = input().lower()
if answer in self.correct:
print('\033[32m'"\nNice job! ?\n")
return True
else:
self.chances -= 1
if self.chances == 0:
print('\33[31m\nIncorrect! ? The correct answer is', self.correct)
return False
else:
print('\33[31m'"\nIncorrect! ? Try again...\n")
# Example setup
score = 0
all_questions = [
Question(
0,
'What is the real name of Batman?',
['A. Bruce Wayne', 'B. Peter Parker', 'C. Bruce Banner', 'D. Bruce Waine'],
['a', 'bruce wayne']
),
Question(
1,
'Another question..',
['A. Answer 1', 'B. Answer 2', 'C. Answer 3', 'etc..'],
['b', '3'],
)
]
for question in all_questions:
question.print()
correct = question.guess()
if correct:
score += 1
我已經(jīng)展示了一個(gè)示例,說(shuō)明如何提出許多問(wèn)題(在列表中),然后打印并一一猜測(cè)所有問(wèn)題。
讓我知道你有什么問(wèn)題(哈)。
添加回答
舉報(bào)