亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

MMMHUHU 2023-12-12 21:35:14
我做了一個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)
查看完整描述

1 回答

?
炎炎設計

TA貢獻1808條經驗 獲得超4個贊

下面是定義“問題”的自定義類的示例 - 然后您可以創建其中的許多問題,并以這種方式重用大量代碼。


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

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


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


查看完整回答
反對 回復 2023-12-12
  • 1 回答
  • 0 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號