如何压缩(或抽象)多个if和elif语句?

时间:2018-03-18 15:51:30

标签: python python-3.x

我正在为Tkinter的假设风险资本家创建一个程序,用于输入去年和去年第二年的业务收入。该程序将总结金额,分析它并分配点(范围从0到18)。 18是满分,这意味着收入很高。 0是最低分,这意味着收入太低。

为了具体在该计划中,我设置了50,000美元的增量(例如,在收入中赚取10万美元到150,000美元之间的任何总价值将增加1点,收入在150,000美元到200,000美元之间的任何总价值将增加2点等等一直到18)。

因为这会占用很多行代码并且效率不高,有没有更好的方法来抽象所有这些?我仍然想保持特异性。

以下是代码:

TotalPoints = 0

def SumOfTwoYearRevenue():
    global TotalPoints
    LastYearRevenue = (float(Revenue_LastYear.get()))
    SecondLastYearRevenue = (float(Revenue_SecondLastYear.get()))

    Sum = LastYearRevenue + SecondLastYearRevenue

    if Sum < 100000:
        pass
    elif Sum >= 100000 and Sum < 150000:
        TotalPoints = TotalPoints + 1
    elif Sum >= 150000 and Sum < 200000:
        TotalPoints = TotalPoints + 2
    elif Sum >= 200000 and Sum < 250000:
        TotalPoints = TotalPoints + 3
    elif Sum >= 250000 and Sum < 300000:
        TotalPoints = TotalPoints + 4
    elif Sum >= 300000 and Sum < 350000:
        TotalPoints = TotalPoints + 5
    elif Sum >= 350000 and Sum < 400000:
        TotalPoints = TotalPoints + 6

#etc... all the way until "TotalPoints = TotalPoints + 18"

2 个答案:

答案 0 :(得分:1)

乍一看,您的代码可以用C语言中的class ElementSerializer < ActiveModel::Serializer attributes :coordinates def coordinates [object.coordinates.x, object.coordinates.y] end end 语句更好地表示,而不是在python中。

然而,如果你仔细观察它,那么你会发现你可能不需要一堆条件语句,并且通过使用类似下面的东西更适合:

switch

希望这有帮助!

答案 1 :(得分:0)

我想这应该有效:

"Name ; Nagesh  V Name ; Savitha Name ; A T Vitalrao\n\nFather's Le Venkatappa Father's Srinivas Father's Thirumagandam\nName: Name: Name:\n\nHouse No.:9/1 House No.:9/C House No.:9/C\n\nAge: 60 Sex: Male Age: 28 Sex: Female Age: 85 Sex: Male\nBCW1799964 BCW1797224 SOH0004515\nName : V Kedarnath Name : K Nalini Name : Sayiraj\n\nFather's Vital rao Husband's V Kedarnath Father's Rudrappa\n\nName: Name: Name:\n\nHouse No.:11 House No.:11 House No.:71\n\nAge: 55 Sex: Male Age: 47 Sex: Female Age: 36 Sex: Male\nSOH4703575 SOH4715249 SOH4703534\nName ; G.Dayala Murthy Name ; G.Anjali Name ; Tamil Selvi\n\nFather's K.Govinda Swamy Husband's K.Govinda Swamy Father's Govinda Swamy\nName: Name: Name:\n\nHouse No.:3 House No.:3 House No.:3\n\nAge: 28 Sex: Male Age: 48 Sex: Female Age: 21 Sex: Female\nSOH4703583 SOH4475547 SOH4475521\nName ; K.Govinda Swamy Name ; Rony Mazumder Name ; Bina Mazumder\nFather's Kuppuswamy Father's SAMIR MAZUMDER Husband's SAMIR MAZUMDER\nName: Name: Name:\n\nHouse No.:3 House No.:3/1 House No.:3/1\n\nAge: 60 Sex: Male Age: 29 Sex: Male Age: 52 Sex: Female\nSOH4476115 SOH4476164 SOH4476198\nName ; Priyanka Mmazumder Name ; Puja Mazumder Name ; Samir Mazumder\nFather's SAMIR MAZUMDER Mother's SAMIR MAZUMDER Father's MANINDRA LAL\nName: Name: Name: MAZUMDER\n\nHouse No.:3/1 House No.:3/1 House No.:3/1\n\nAge:"
相关问题