[英]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)
暗示:
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.