簡體   English   中英

如何使用多個 else 語句?

[英]how can I use multiple else statements?

我想在我的 class 方法中使用一些else語句:

class Musician :
    def __initiate__(self,name, instrument, years_playing, practice_hours):
        self.name = name
        self.instrument =instrument
        self.years_playing = years_playing
        self.practice_hours = practice_hours
        # self.level = int(self.practice_hours*self.years_playing)

    def level(self):
        if self.practice_hours <= 1 and self.years_playing <=1:
            print (self.name,'is a beginner')
        else:
            self.practice_hours <=2 and self.years_playing <=2
            print (self.name,'is an intermediate')
        else:
            self.practice_hours <= 3 and self.years_playing <=3
            return (self.name, 'is an expert')  

player_1 = Musician('Don', 'guitar', 1,3)       

player_1.level()

您的代碼有很多問題。 您遇到的實際問題似乎是關於在您嘗試使用else的地方使用elif 一般結構是

if condition:
    something should happen
elif other_codition:
    things which should be done in this case
elif third_condition:
    other things
else:
    unconditionally do this if none of the conditions above were true

第一個之后的所有分支都是可選的。

您將printreturn混合在一起,我猜您的意思是__init__ 這是修復代碼的嘗試。

class Musician:
    def __init__(self, name, instrument, years_playing, practice_hours):
        self.name = name
        self.instrument =instrument
        self.years_playing = years_playing
        self.practice_hours = practice_hours
        # self.level = int(self.practice_hours*self.years_playing)

    def level(self):
        if self.practice_hours <= 1 and self.years_playing <= 1:
            return "beginner"
        elif self.practice_hours <= 2 and self.years_playing <= 2:
            return "intermediate"
        elif self.practice_hours <= 3 and self.years_playing <= 3:
            return "expert"

player_1 = Musician('Don', 'guitar', 1, 3)       

lvl = player_1.level()
print(f"the level of {player_1.name} is {lvl}")

__init__是創建新實例時調用的方法的保留名稱; 您不能使用不同的名稱並希望在 shme 情況下調用它。

如果沒有一個條件為真, level function 仍將返回None ,但如何解決這個問題取決於我不知道的標准。 也許更好的設計是檢查“專家”或“中級”,否則如果兩者都不正確,則始終返回“初學者”。

    def level(self):
        if self.practice_hours > 2 and self.years_playing > 2:
            return "expert"
        elif self.practice_hours > 1 and self.years_playing > 1:
            return "intermediate"
        # else
        return "beginner"

您可以使用 bisect 來實現相同的目的,而無需使用 if

import bisect

def level(self):

    level_dict = {0 : 'is a beginner', 1 : 'is an intermediate', 2 : 'is an expert'}
    grade_ranges = [(0, 1), (1, 2), (2, 3)]
    points, grade = zip(*grade_ranges)
    return self.name + level_dict[bisect.bisect(points, self.practice_hours)-1]

暫無
暫無

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

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