本文通过计算复利来体验python .format()格式化输出:
每年定投10万元,投32年,年利率4%。 格式化输出如下:
"""
变量说明:
cost_yearly #每年定投成本
annual_interest_rate #年化利率
year #第XX年
"""
def earn(cost_yearly,annual_interest_rate):
get = cost_yearly*(1+annual_interest_rate)
print('| 第{0:0>2}年 |{1:^8.2f}|{2:^10.0%}|{3:^10.2f}|'.format(
year,
cost_yearly,
annual_interest_rate,
get
)
)
return(get+10)
if __name__ == '__main__':
cost_yearly = 10 #首年投资10万元
annual_interest_rate=0.04 #年化利率4%
line = "-"* 41
print(line)
print("| 年限 | 年投入 | 年化利率 | 当年本息 |")
print(line)
for year in range(1,33):
cost_yearly = earn(cost_yearly,annual_interest_rate)
print(line)
input()
format()使用说明如下: