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

月度预算分析Python程序函数代码补全求助

月度预算分析程序补全代码

以下是补全并完善后的完整Python代码,修复了语法错误并实现了所有核心功能:

def DescribeProgram():
    print("""\
This program uses a for loop to monitor your budget.
The program will prompt you to enter your budget, and amount spent
for a certain month and calculate if you were under or over budget.
You will have the option of choosing how many months you would like to
monitor.
""")

def GetMonths():
    # 确保输入为大于0的有效整数
    while True:
        try:
            months = int(input("Enter the number of months you want to analyze: "))
            if months > 0:
                return months
            print("Please enter an integer greater than 0.")
        except ValueError:
            print("Invalid input, please enter an integer.")

def GetMonthBudgetandSpent(month):
    # 获取当月预算,校验输入有效性
    while True:
        try:
            mo_budget = float(input(f"Enter budget for month {month}: "))
            if mo_budget >= 0:
                break
            print("Budget cannot be negative.")
        except ValueError:
            print("Invalid input, please enter a number.")
    
    # 获取当月支出,校验输入有效性
    while True:
        try:
            mo_spent = float(input(f"Enter amount spent for month {month}: "))
            if mo_spent >= 0:
                return mo_budget, mo_spent
            print("Spending cannot be negative.")
        except ValueError:
            print("Invalid input, please enter a number.")

def AnalyzeBudget(months):
    total_budget = 0.0
    total_spent = 0.0
    for month in range(1, months + 1):
        print(f"\nMonth {month}:")
        print("=======")
        mo_budget, mo_spent = GetMonthBudgetandSpent(month)
        total_budget += mo_budget
        total_spent += mo_spent
        
        # 计算并展示当月预算情况
        diff = mo_budget - mo_spent
        if diff > 0:
            print(f"Under budget by ${diff:.2f}")
        elif diff < 0:
            print(f"Over budget by ${abs(diff):.2f}")
        else:
            print("Budget matched exactly.")
    
    # 展示整体预算统计
    print("\n======= Total Summary =======")
    total_diff = total_budget - total_spent
    print(f"Total Budget: ${total_budget:.2f}")
    print(f"Total Spent: ${total_spent:.2f}")
    if total_diff > 0:
        print(f"Overall under budget by ${total_diff:.2f}")
    elif total_diff < 0:
        print(f"Overall over budget by ${abs(total_diff):.2f}")
    else:
        print("Total budget matched total spending exactly.")

def main():
    DescribeProgram()
    months = GetMonths()
    AnalyzeBudget(months)

if __name__ == "__main__":
    main()

补全细节说明

  • GetMonths函数:
    修复了缺失def关键字、输入语句括号未闭合的语法错误;增加输入合法性校验,确保用户输入大于0的有效整数,避免无效输入导致程序异常。
  • GetMonthBudgetandSpent函数:
    补加def关键字,实现了用户输入当月预算和支出的逻辑;增加输入校验,确保输入为非负数的有效数字,提升程序健壮性。
  • AnalyzeBudget函数:
    修复了缺失def关键字、缩进错误的问题;新增当月预算差值计算与结果展示,同时统计总预算和总支出,最后输出整体预算情况。
  • 主程序入口:
    增加if __name__ == "__main__":判断,确保程序作为脚本直接运行时才启动主逻辑,符合Python规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 03:31:37