python写一个房贷计算器1-30年
时间: 2024-09-26 22:10:27 浏览: 46
在Python中编写一个房贷计算器,通常会涉及用户输入贷款金额、年利率、贷款期限等信息,并计算每月还款额以及总利息支出。这里是一个简单的函数示例,假设采用等额本息还款法:
```python
def mortgage_calculator(principal, annual_interest_rate, loan_term_years):
# 将年利率转换为小数
monthly_interest_rate = annual_interest_rate / 12
total_months = loan_term_years * 12
# 等额本息还款公式
monthly_payment = principal * (monthly_interest_rate * (1 + monthly_interest_rate)**total_months) / ((1 + monthly_interest_rate)**total_months - 1)
# 计算总利息
total_interest = monthly_payment * total_months - principal
return {
"monthly_payment": round(monthly_payment, 2),
"total_interest": round(total_interest, 2)
}
# 示例使用
principal = float(input("请输入贷款本金(万元): "))
annual_interest_rate = float(input("请输入年利率(百分比): ")) / 100
loan_term_years = int(input("请输入贷款年限(年): "))
result = mortgage_calculator(principal, annual_interest_rate, loan_term_years)
print(f"月供: {result['monthly_payment']}万元")
print(f"总利息: {result['total_interest']}万元")
阅读全文