案例学习
通过案例将Python的理论学习和实践结合在一起。案例的作用是用来做分析揣摩以及熟练训练的方式
对于技能型的编程,要达到脱口而出,出手就成的熟练程度。将分析过程内化以及将表达形成肌肉记忆
案例的类别
案例的归属大类
数据处理案例
数据处理流程案例
数据流案例--数据采集 -数据存储 -数据计算--数据输出
案例的代码示例
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# ---------------------------
def calc_average_capital_interest(money, rate, month_time):
# 每月还款
repayment = rate * (1 + rate) ** month_time / ((1 + rate) ** month_time - 1) * money
# 总利息
total_interest = repayment * month_time - money
remaining = []
inter_repayment = []
for n in range(1, month_time + 1):
# 第n月还款本金
repayment_capital = rate * (1 + rate) ** (n - 1) / ((1 + rate) ** month_time - 1) * money
remaining.append(repayment_capital)
# 第n月还款利息
repayment_interest = repayment - repayment_capital
inter_repayment.append(repayment_interest)
# 剩余需还本金
remaining_capital = money - sum(remaining)
print("等额本息-第:%d 期,还款:%0.2f,还款本金是:%0.2f,月供利息:%0.2f,剩余本金:%0.2f, 累计利息:%0.2f,累计还款: %0.2f"
% (n, repayment, repayment_capital, repayment_interest, remaining_capital, sum(inter_repayment), repayment*n))
print('贷款年限 %d 年利息 %0.2f 商贷金额 %0.2f 万元' % (month_time / 12, rate * (12 * 100), money / 10000))
print('贷款年限 %d 每月还款金额是:%0.2f 利息总额 %0.2f 万元' % (month_time / 12, repayment, total_interest / 10000))
def calc_average_capital(money, rate ,month_time):
# 贷款额为money,月利率为rate,还款月数为month_time
sigs_interest = []
# 每月应还本金
repayment_capital = money / month_time
for m in range(1, month_time + 1):
# 每月应还利息
repayment_interest = (money - repayment_capital * (m - 1)) * rate
# 每月应还总金额
repayment = repayment_capital + repayment_interest
# 剩余本金
remaining = money - m * repayment_capital
sigs_interest.append(repayment_interest)
# 累计利息
cal_interest = sum(sigs_interest)
# 累计还款金额
acc_amt = repayment_capital*m+cal_interest
print("等额本金-第:%d期,还款:%0.2f,还款本金是:%0.2f,月供利息:%0.2f,剩余本金:%0.2f, 累计利息:%0.2f,累计还款: %0.2f"
% (m, repayment, repayment_capital, repayment_interest, remaining, cal_interest, acc_amt))
total_interest = sum(sigs_interest) / 10000
print(
'等额本金-贷款年限 %d 年利息 %0.2f 商贷金额 %0.2f 万元 利息 %0.2f 万元 '
% (month_time / 12, rate * (12 * 100), money / 10000, total_interest))
if __name__ == "__main__":
# 月供本金 月供利息 剩余本金 剩余利息 累计利息 累计本金 累计还款
loan_money = 10 * 10000
# 月利率,将年利率5.15%转换为0.0515,除以12转为月利率
loan_rate = 5.15 / (12 * 100)
# 贷款年限年转换为月,总月数
loan_month_time = 30 * 12
flag = 2
if flag == 1:
calc_average_capital_interest(loan_money, loan_rate, loan_month_time)
else:
calc_average_capital(loan_money, loan_rate, loan_month_time)