import math
import random
def input_limit(input_name, input_range):
if input_range[0] <= input_name <= input_range[-1]:
return True
else:
print('请输入在', input_range[0],'和', input_range[-1], '之间的数值')
return False
def bank_loan():
print('*'*20+'欢迎使用房贷计算器!'+'*'*20)
try:
while True:
loan_base = float(input('您购房共贷款金额(万元):'))
if input_limit(loan_base, [0,99999999999]):
print('*'*15, loan_base, '万元'+'*'*5)
break
while True:
loan_rate = float(input('您的贷款年利率是(%):'))
if input_limit(loan_rate, [0,100]):
print('*'*15, loan_rate,'%'+'*'*5)
break
while True:
loan_way = int(input('您的还贷方式是:1.等额本金/2.等额本息'))
if input_limit(loan_way, [1,2]):
print('*' * 15, '等额本金'+'*' * 5) if loan_way == 1 else print('*'*15+'等额本息'+'*'*5)
break
while True:
loan_term = int(input('您的还款期限(年)是:'))
if input_limit(loan_term, [1,140]):
print('*'*15, loan_term,'年'+'*'*5)
break
except(ValueError, EOFError, TypeError):
print('请输入正确的数字格式')
else:
loan_base = loan_base*10000
loan_rate = loan_rate/100
print('您一共贷款人民币', loan_base, '元,期限是', loan_term, '年。')
print('您选择的还贷方式是:')
print('等额本金') if loan_way == 1 else print('等额本息')
print('以下是系统为您计算的每月预还款数额,请查收:')
if loan_way == 1:
n=1
loan_sum_1 = 0
while n <= 12*loan_term:
base_1 = loan_base/(12*loan_term)
loan_n = ((loan_base - base_1*(n-1))*loan_rate/12)
print('第',n,'个月:您已还款', loan_sum_1,'元,您本月需还款:',loan_n + base_1, '元,其中包含本月利息', loan_n ,'元;')
loan_sum_1 = loan_sum_1 + loan_n + base_1
n = n+1
print('您共还款', loan_sum_1,'元,历时',n-1,'个月,总利息为:',loan_sum_1 - loan_base,'元,月平均利息为',(loan_sum_1 - loan_base)/(n-1),'元')
else:
k = 1
loan_sum_2 = 0
base_2_rate = 0
rate = loan_rate/12
term = 12*loan_term
base_2 = (loan_base*rate*math.pow((1+rate),term))/(math.pow((1+rate),term)-1)
while k <= term:
base_2_rate = loan_base*rate*pow((1+rate),k) - base_2*(pow((1+rate),k)-1)
print('第',k,'个月:您已还款', loan_sum_2,'元,您本月需还款:',base_2, '元,其中包含本月利息', base_2_rate ,'元;')
loan_sum_2 = loan_sum_2 + base_2
k = k+1
print('您共还款', loan_sum_2, '元,历时', k - 1, '个月,总利息为:', loan_sum_2 - loan_base, '元,月平均利息为',
(loan_sum_2 - loan_base) / (k - 1), '元')
bank_loan()
bank_loan()