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

Python脚本计算贷款金额时出现TypeError错误的解决咨询

修复Python贷款计算程序的类型错误

我正在编写一个Python程序,用于根据月还款额、年利率和贷款期限计算最大贷款金额。当前代码如下:

while check == 1:
    monthly_payment = float(input("Enter how much you can pay per month: "))
    annual_interest = float(input("Enter the bank's annual interest rate (in %): "))
    years = input("Enter how many years you want the loan for: ")


    r = annual_interest / 100 / 12
    n = years * 12  
    if r == 0:
        loan_amount = monthly_payment * n
    else:
        loan_amount = monthly_payment * (1 - (1 + r) ** -n) / r

    print("\n-----------------------------")
    print("Maximum loan amount you can get: "+str(round(loan_amount, 2)))
    print("-----------------------------")
    check = input("Do you want to do the calculation again? 1 - yes  0 - no:  ")

运行代码时出现如下错误:

Traceback (most recent call last):
  File "C:\Users\Alex\PyCharmMiscProject\test3.py", line 13, in <module>
    loan_amount = monthly_payment * (1 - (1 + r) ** -n) / r
                                                    ^^
TypeError: bad operand type for unary -: 'str'

错误原因

input()函数默认返回字符串类型,你获取years时未做类型转换,导致n = years * 12实际是把字符串重复12次(比如输入5,n会变成"555555555555")。后续计算-n时,Python无法对字符串执行一元负号操作,因此抛出类型错误。

另外还有隐藏问题:循环末尾获取的check是字符串类型,下次循环时check == 1会判断不成立,导致无法再次执行计算。

修复步骤

  1. 将years转换为数值类型:推荐用float以支持非整数年限(如5.5年),若仅接受整数年限则用int。
  2. 将循环末尾获取的check转换为整数类型,确保循环条件能正常判断。

修正后的完整代码

check = 1  # 初始化循环变量
while check == 1:
    monthly_payment = float(input("Enter how much you can pay per month: "))
    annual_interest = float(input("Enter the bank's annual interest rate (in %): "))
    # 将years转换为float类型
    years = float(input("Enter how many years you want the loan for: "))

    r = annual_interest / 100 / 12
    n = years * 12  
    if r == 0:
        loan_amount = monthly_payment * n
    else:
        loan_amount = monthly_payment * (1 - (1 + r) ** -n) / r

    print("\n-----------------------------")
    # 用f-string替代字符串拼接,更简洁易读
    print(f"Maximum loan amount you can get: {round(loan_amount, 2)}")
    print("-----------------------------")
    # 将check转换为int类型
    check = int(input("Do you want to do the calculation again? 1 - yes  0 - no:  "))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 02:52:37