gpt4 book ai didi

python - 我怎样才能简化我的 python 测验? (让它更短)

转载 作者:行者123 更新时间:2023-12-04 15:15:09 25 4
gpt4 key购买 nike

我做了一个 Python 测验,大约有 500 行。我想知道如何缩短它并简化代码。这是我在测验中的一个问题的例子

while counter<3:
def question(question,choices):
print(question)
for question in choices:
print(question)

print('\033[0m'"____________________________________________________________\n")

question("Question 1. What is the real name of Batman?", ["A. Bruce Wayne", "B. Peter Parker", "C. Bruce Banner", "D. Bruce Waine"])
answer = input().lower()

if answer == "a":
print('\033[32m'"\nNice job! ✔\n")
score = score +1
counter = 4
elif answer == "bruce wayne":
print('\033[32m'"\nGreat work! ✔\n")
counter = 4
break
else:
score = score - 1
counter = counter +1
if counter ==3:
print('\33[31m'"\nIncorrect! ✘ The correct answer is A. Bruce Wayne\n")
elif counter ==1 or 2:
print('\33[31m'"\nIncorrect! ✘ Try again...\n")
print('\033[0m''\033[04m'"Your score is ",score)

最佳答案

下面是一个自定义类的示例,它定义了一个“问题”——然后您可以制作许多这样的问题,并通过这种方式重用大量代码。

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

我已经展示了一个示例,说明您如何(在列表中)提出许多问题,然后打印并逐一猜测所有问题。

让我知道您有什么问题 (ha)。

关于python - 我怎样才能简化我的 python 测验? (让它更短),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64474783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com