Python储蓄计算器报错:TypeError: can only concatenate str (not "int") to str
储蓄计算器TypeError问题解决
问题描述
开发简易储蓄计算器时添加用户输入功能后触发错误:TypeError: can only concatenate str (not "int") to str,实现代码如下:
def save(): # Set the target savings amount and the number of months target_savings = input("Please input your savings goal.") print("") months = input("Please input how many months you want to take to reach this goal.") print("") # Initialize the current savings amount current_savings = 0 # Set monthly income monthly_income = input("Please input your monthly income") print("") # Loop through each month for month in range(1, months + 1): # Get the monthly expenses expenses = float(input("Enter expenses for month {month}: $")) # Calculate the monthly savings monthly_savings = monthly_income - expenses # Add the monthly savings to the current savings current_savings += monthly_savings # Check if the current savings is enough to reach the target savings if current_savings >= target_savings: print(f"Congratulations! You reached your savings goal of ${target_savings} in month {month}.") break else: print(f"Month {month}: Savings = ${current_savings}, Goal = ${target_savings}") # Call the function to start the savings tracker save()
报错信息:
for month in range(1, months + 1): TypeError: can only concatenate str (not "int") to str
错误原因
input()函数返回的是字符串类型,而range()的参数需要整数。代码中months是用户输入的字符串,执行months + 1时会尝试把字符串和整数拼接,触发类型错误。- 除此之外,
target_savings和monthly_income也是字符串类型,后续执行monthly_income - expenses、current_savings >= target_savings时也会触发类型错误,只是当前报错先出现在循环部分。
修复方案
将用户输入的数值类变量转换为对应的数据类型:
months转换为整数int()target_savings和monthly_income转换为浮点数float()(支持小数金额)
修复后的完整代码:
def save(): # Set the target savings amount and the number of months target_savings = float(input("Please input your savings goal.")) print("") months = int(input("Please input how many months you want to take to reach this goal.")) print("") # Initialize the current savings amount current_savings = 0.0 # Set monthly income monthly_income = float(input("Please input your monthly income")) print("") # Loop through each month for month in range(1, months + 1): # Get the monthly expenses expenses = float(input(f"Enter expenses for month {month}: $")) # Calculate the monthly savings monthly_savings = monthly_income - expenses # Add the monthly savings to the current savings current_savings += monthly_savings # Check if the current savings is enough to reach the target savings if current_savings >= target_savings: print(f"Congratulations! You reached your savings goal of ${target_savings:.2f} in month {month}.") break else: print(f"Month {month}: Savings = ${current_savings:.2f}, Goal = ${target_savings:.2f}") # Call the function to start the savings tracker save()
额外优化:添加:.2f格式化输出金额,保留两位小数,更符合金额显示习惯。
内容的提问来源于stack exchange,提问作者Kaleb Elley
相关产品推荐
相关产品推荐

