Python月度预算循环程序报错,请求问题排查
Python月度预算程序报错排查与修复
你的代码核心问题是类型不匹配,执行时会触发TypeError,以下是具体问题和修复方案:
主要错误点
- 整数与字符串直接拼接:
for循环里的month是整数类型,不能直接和字符串用+拼接(比如"Enter amount budgeted for month "+month+":"),必须先把month转为字符串。 - 浮点数与字符串直接拼接:计算出的
underBy/overBy是浮点数,直接和字符串拼接同样会触发类型错误。 - 整数与字符串比较:
if month == "1"中,month是整数,和字符串"1"永远不相等,这个判断逻辑根本不会执行。 - 部分
print语句有多余换行符,导致输出格式混乱。
修复后的完整代码
print(""" This program will prompt you to enter your budget, and amount spent for a certain month and calculate if your were under or over budget. You will have the option of choosing how many months you would like to monitor. """) AmountSpent = 0 Budget = 0 numMonths = int(input("Enter the number of months you would like to monitor:")) while numMonths < 0: print("Negative value detected!") numMonths = int(input("Enter the number of months you would like to monitor:")) for month in range(1, numMonths+1): print("=====================================") # 用f-string自动处理类型转换,避免拼接错误 AmountBudgeted = float(input(f"Enter amount budgeted for month {month}:")) while AmountBudgeted < 0: print("Negative value detected!") AmountBudgeted = float(input(f"Enter amount budgeted for month {month}:")) AmountSpent = float(input(f"Enter amount spent for month {month}:")) while AmountSpent < 0: print("Negative value detected!") AmountSpent = float(input(f"Enter amount spent for month {month}:")) if AmountSpent <= AmountBudgeted: underBy = AmountBudgeted - AmountSpent # 用f-string格式化浮点数输出,避免类型错误 print(f"Under budget by {underBy}") else: overBy = AmountSpent - AmountBudgeted print(f"Over budget by {overBy}") # 把字符串"1"改为整数1,让判断逻辑生效 if month == 1: print(f'Your budget is {AmountBudgeted}.')
关键修复说明
- 所有输入提示改用f-string(
f"..."),自动完成变量类型转换,彻底避免手动拼接的类型问题。 - 打印金额差值时同样用f-string,直接格式化浮点数输出。
- 修正月份判断的类型匹配问题,让第一个月的预算提示正常触发。
- 移除了
print语句中多余的换行符,规范输出格式。
内容的提问来源于stack exchange,提问作者user20391565
相关产品推荐
相关产品推荐

