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

Python编写投资复利计算代码触发TypeError字符串拼接错误怎么解决

报错原因

你代码里的字符串拼接操作仅对金额变量做了字符串转换,代表年份的(i+1)仍是整数类型,直接和字符串用+拼接就会触发该类型错误,和后面的金额是否转字符串无关。

比如以下代码段:

print("Starting Balance: for year " + (i+1)+"$"+str(Starting_balance))

其中"Starting Balance: for year "是字符串,后面紧跟的(i+1)是整数,二者直接拼接就会报错。


修复方案

1. 解决类型报错

有两种常用实现方式:

  • 手动转换年份类型:把所有拼接语句里的(i+1)统一修改为str(i+1)
  • 更推荐使用Python f-string格式化输出,无需手动做类型转换,写法更简洁不易出错

2. 修复复利计算逻辑

你当前代码还是每年复用初始的InvestAmount计算利息,没有更新本金值,就算解决了类型报错,收益仍然不会累加。需要在每年循环结束时,把当年的结束余额赋值给InvestAmount,作为下一年的初始本金。


修复后完整代码

InvestAmount = int(input("Enter the intial investment amount: "))
Years = int(input("Enter the number of years to invest: "))
Rate = float(input("Enter the intrest rate (as %): "))
TotalInterestEarned = 0
for i in range(Years):
    # 记录当年起始余额,即上一年的结束余额
    Starting_balance = InvestAmount
    InterestEarned = round(Starting_balance*(Rate/100),2)
    EndingBal = round(Starting_balance + InterestEarned , 2)
    # 累计总收益
    TotalInterestEarned += InterestEarned
    # f-string格式化输出,无需手动转类型
    print(f"Starting Balance for year {i+1}: ${Starting_balance}")    
    print(f"Ending balance for year {i+1}: ${EndingBal}")
    print(f"Interest earned for year {i+1}: ${InterestEarned}")
    print(f"Total interest earned up to year {i+1}: ${round(TotalInterestEarned,2)}\n")
    # 更新下一年的本金
    InvestAmount = EndingBal

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:06:02