簡體   English   中英

如何簡化我的 Python 測驗? (讓它更短)

[英]How can i simplify my python quiz? (make it shorter)

我做了一個 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

我已經展示了一個示例,說明您將如何提出許多問題(在列表中),然后逐一打印並猜測所有問題。

讓我知道你有什么問題(哈)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM