Home > Net >  How do i make this repetitive code into a function?
How do i make this repetitive code into a function?

Time:07-15

how do i change this 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}.")

CodePudding user response:

Hint:

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

CodePudding user response:

I would do it this way:

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. Create a dictionary with possible answers as keys and their lists as values. Do the same for totals.
  2. Create a function which receives an answer. Make the answer lower letters.
  3. Save list which is important for this answer into a variable. Do the same for total.
  4. Create a function for total and mean calculations. Pass the list and the total to it. 5 . Create a function for comparing. Pass year, list, mean and answer to it.
  • Related