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

求助:如何将月度预算Python代码拆分为def函数?

月度预算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 your were under or over budget.
You will have the option of choosing how many months you would like to
monitor.\n""")

def GetMonths():
    """获取用户输入的有效月份数(非负数)"""
    while True:
        try:
            num_months = int(input("Enter the number of months you would like to monitor:"))
            if num_months >= 0:
                return num_months
            print("\nNegative value detected!")
        except ValueError:
            print("Please enter a valid integer.")

def get_positive_float(prompt):
    """获取正数类型的输入,用于预算和支出金额"""
    while True:
        try:
            value = float(input(prompt))
            if value >= 0:
                return value
            print("Negative value detected!")
        except ValueError:
            print("Please enter a valid number.")

def calculate_budget_status(budgeted, spent):
    """计算并输出当月预算结余或超支情况"""
    if spent <= budgeted:
        under_amount = budgeted - spent
        print(f"Good Job! You are under budget by {under_amount:.2f}")
    else:
        over_amount = spent - budgeted
        print(f"Oops! You're over budget by {over_amount:.2f}")

def main():
    DescribeProgram()
    num_months = GetMonths()
    
    for month in range(1, num_months + 1):
        print("\n=====================================")
        amount_budgeted = get_positive_float(f"Enter amount budgeted for month {month}:")
        amount_spent = get_positive_float(f"Enter amount spent for month {month}:")
        
        calculate_budget_status(amount_budgeted, amount_spent)
        
        # 修复原代码中字符串与整数比较的bug
        if month == 1:
            print(f'Your budget for the first month is {amount_budgeted:.2f}.')

if __name__ == "__main__":
    main()

函数说明

  • DescribeProgram():负责打印程序的功能介绍,单独抽离后便于维护和修改说明文本
  • GetMonths():专门处理月份数的输入验证,确保用户输入非负整数,包含异常处理避免输入非数字时崩溃
  • get_positive_float():通用函数,复用预算和支出金额的输入逻辑,减少重复代码
  • calculate_budget_status():专注于预算计算和结果输出,将业务逻辑与输入逻辑分离
  • main():作为程序入口,串联所有函数调用,让流程更清晰

内容的提问来源于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:01:01