繁体   English   中英

我如何将这个重复的代码变成一个函数?

[英]How do i make this repetitive code into a function?

我如何将其更改为函数?

if sell in ["Dividends","dividends"]:
    for x in range(1,13):
        TotalD=TotalD+int(dividends[x])
        MeanD=TotalD/12
    for yr,div in zip(year,dividends):
        D=MeanD*1.2
        D=str(D)
        if div>D:
            print(f"In Year {yr} the income in Dividends is (S$){div}.")

elif sell in ["Interests","interests"]:
    for x in range(1,13):
        TotalI=TotalI+int(interests[x])
        MeanI=TotalI/12
        I=MeanI*1.20
    for yr,ints in zip(year,interests):
        I=str(I)
        if ints>I:
            print(f"In Year {yr} the income in Interests is (S$){ints}.")
            
            
elif sell in ["Others","others"]:
    for x in range(1,13):
        TotalO=TotalO+int(othertypes[x])
        MeanO=TotalO/12
    for yr,ot in zip(year,othertypes):
        O=MeanO*1.2
        O=str(O)
        if ot>O:
            print(f"In Year {yr} the income in Other Types is (S$){ot}.")

我会这样做:

lists = {"dividents": dividents, "interests": interests, "others": othertypes}
totals = {"dividents": TotalD, "interests": TotalI, "others": TotalO}

def total_and_mean(total, lst):
    for x in range(1, 13):
        total += int(lst[x])
    return total, total / 12


def comparing(year, lst, mean, typ):
    typ = typ.capitalize()
    for yr, div in zip(year, lst):
        D = mean * 1.2
        D = str(D)
        if div > "0":
            print(f"In Year {yr} the income in {typ} is (S$){div}.")


def main_function(s):
    s = s.lower()

    this_list = lists[s]
    this_total = totals[s]

    total, mean = total_and_mean(this_total, this_list)
    comparing(year, this_list, mean, s)
  1. 创建一个字典,其中可能的答案作为键,它们的列表作为值。 对总数执行相同的操作。
  2. 创建一个接收答案的函数。 使答案小写。
  3. 将对此答案很重要的列表保存到变量中。 对总数做同样的事情。
  4. 为总计和平均值计算创建一个函数。 将列表和总数传递给它。 5. 创建一个比较函数。 过年,列出,意思并回答它。

暗示:

def function(names, types):
    if sell in names:
        for x in range(1,13):
            Total=Total+int(types[x])
            Mean=Total/12
        for yr,div in zip(year, types):
            M=Mean*1.2
            M=str(M)
            if div>M:
                print(f"In Year {yr} the income in " + names[0] + "is (S$){div}.")
        return True
    return False

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM