You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python贷款计算器高利率下运行卡死报KeyboardInterrupt错误求助

问题原因
  • 核心逻辑漏洞导致死循环:当每月产生的利息高于当月还款额时,剩余未还本金会持续上涨,永远满足不了while price > 0的退出条件,程序就会一直运行无输出,手动终止后就会返回KeyboardInterrupt报错。
    拿你提供的测试参数计算验证:
    初始未还本金为22500元,月利率18%,单月利息为22500 * 0.18 = 4050元,当月还款3000元后,剩余本金为22500 + 4050 - 3000 = 23550元,比初始本金更高,后续每个月本金都会越滚越多,永远不会小于等于0。
  • 次要问题:get_months函数直接依赖全局变量传值,不符合封装规范,容易出现作用域相关的隐藏bug。
  • 额外注意:很多用户会混淆年利率和月利率,如果18%是年利率,实际月利率应为18%/12 = 1.5%,输入错误的利率单位也会触发该问题。
解决方法
  1. 新增还款能力前置校验:进入循环前先判断月还款额是否足够覆盖首月利息,如果不够直接提示用户,避免死循环。
  2. 新增最大还款周期限制:比如设置最多计算30年(360个月),超过上限直接返回提示,避免极端情况卡死。
  3. 优化函数传参逻辑,避免依赖全局变量。

修改后的可正常运行代码如下:

def get_months(price, down_payment, interest_rate, installments):
    counter = 0
    remaining = price - down_payment
    # 前置校验:月还款不足以覆盖利息,永远还不清
    first_month_interest = remaining * interest_rate
    if first_month_interest >= installments:
        return -1
    while remaining > 0:
        remaining = remaining * (1 + interest_rate) - installments
        counter += 1
        # 最大周期限制:超过30年直接返回提示
        if counter > 360:
            return -2
    return counter


if __name__ == '__main__':
    price = float(input("Enter price here: "))
    interest_rate = float(input("Enter interest rate here: %")) / 100
    while interest_rate < 0:
        interest_rate = float(input('Invalid interest rate please try again: %')) / 100
    down_payment = int(input("Enter your down payment here: $"))
    while down_payment > price or down_payment < 0:
        down_payment = int(input('Invalid down payment please try again: $'))

    choice = input("Decision based on Installments (i) or Months to finish (m), please write i or m: ").lower()
    if choice == 'm':
        print('m')
    elif choice == 'i':
        installments = int(input("What's your monthly installment budget: "))
        months_to_finish = get_months(price, down_payment, interest_rate, installments)
        if months_to_finish == -1:
            print("月还款额不足以覆盖当月利息,债务会持续增长,无法还清,请提高月还款额")
        elif months_to_finish == -2:
            print("还款周期超过30年,请提高月还款额")
        else:
            print(f"It will take {months_to_finish} months to finish your purchase.")
    else:
        print('Invalid choice program ended')

如果是利率单位输错的情况,把18%的年利率换算成1.5%的月利率输入,用你的测试参数计算得到的结果为9个月即可还清。

内容的提问来源于stack exchange,提问作者Khaled Taha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 00:36:03