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

Python首个预算项目需求:确保分类预算分配值不超self.amtt

解决预算总分配不超过存款的问题

这是我开发的第一个Python项目,需求是确保**食品(Food)、服装(Cloth)、娱乐(Entertainment)**三类预算的总分配值不超过存款金额self.amtt。当前代码如下:

class budgetapp():

    def __init__(self,Deposit_amtt, Food, Cloth, Entertainment):
        self.amtt = Deposit_amtt
        self.Food = Food
        self.Cloth = Cloth
        self.Entertainment = Entertainment

    def withdrawal(self):

        for i in range (0,1):
            print('Press 1 for Food\n')

            print('Press 2 for Cloth\n')

            print('Press 3 for Entertainment\n')

        choice = int(input('Which Budget Category do you want to withdraw From?: '))

        if choice == 1:
            
            amt_withdrawal = float(input("How Much do you want to withdraw: "))
        
            if amt_withdrawal>=0 and amt_withdrawal<= self.Food:
                print("Withdrawal Successful")

            elif amt_withdrawal > self.Food:
                print("Insufficient Balance")
            
            else:
                print("Negative values cannot be withdrawn")

        elif choice == 2:

            amt_withdrawal = float(input("How Much do you want to withdraw: "))
            
        
            if amt_withdrawal>=0 and amt_withdrawal<= self.Cloth:
                print("Withdrawal Successful")

            elif amt_withdrawal > self.Cloth:
                print("Insufficient Balance")

            else:
                print("Negative values cannot be withdrawn")

        elif choice == 3:
        
            amt_withdrawal = float(input("How Much do you want to withdraw: "))
        
            if amt_withdrawal>=0 and amt_withdrawal<= self.Entertainment:
                print("Withdrawal Successful")

            elif amt_withdrawal > self.Entertainment:
                print("Insufficient Balance")
            
            else:
                print("Negative values cannot be withdrawn")

        else:  
            print('Invalid choice. Options are between 1-3 only')


budg = budgetapp(float(input("Enter an amount to deposit: ")),
                 float(input("What percentage of total amount do you want to allocate to food: ")), 
                 float(input("What percentage of total amount do you want to allocate to cloth: ")),
                 float(input("What percentage of total amount do you want to allocate to Entertainment: ")))
budg.withdrawal()

问题分析

当前代码存在两个核心问题:

  1. 初始化时直接将用户输入的百分比数值赋值给预算变量,未转换为对应存款的实际金额,逻辑不符合预期
  2. 未验证三类预算的总和是否超过存款金额self.amtt,无法满足核心需求

修改后的代码

class BudgetApp():
    def __init__(self, deposit_amtt, food_percent, cloth_percent, entertainment_percent):
        self.amtt = deposit_amtt
        
        # 将百分比转换为实际预算金额
        self.food = (food_percent / 100) * deposit_amtt
        self.cloth = (cloth_percent / 100) * deposit_amtt
        self.entertainment = (entertainment_percent / 100) * deposit_amtt
        
        # 验证总预算是否超过存款
        total_allocated = self.food + self.cloth + self.entertainment
        if total_allocated > self.amtt:
            raise ValueError(f"总预算分配({total_allocated:.2f})超过存款金额({self.amtt:.2f}),请重新调整比例")

    def withdrawal(self):
        # 简化菜单输出
        print("1. 食品")
        print("2. 服装")
        print("3. 娱乐")
        
        # 处理非数字输入
        try:
            choice = int(input("请选择取款的预算类别:"))
        except ValueError:
            print("无效输入,请输入1-3之间的数字")
            return
        
        # 统一获取对应类别余额和名称
        if choice == 1:
            category_balance = self.food
            category_name = "食品"
        elif choice == 2:
            category_balance = self.cloth
            category_name = "服装"
        elif choice == 3:
            category_balance = self.entertainment
            category_name = "娱乐"
        else:
            print("无效选项,仅可选择1-3")
            return
        
        # 处理取款金额输入
        try:
            amt_withdrawal = float(input("请输入取款金额:"))
        except ValueError:
            print("无效金额,请输入数字")
            return
        
        # 金额校验与余额更新
        if amt_withdrawal < 0:
            print("无法提取负数金额")
        elif amt_withdrawal > category_balance:
            print(f"{category_name}预算余额不足")
        else:
            print("取款成功")
            # 更新对应类别预算余额
            if choice == 1:
                self.food -= amt_withdrawal
            elif choice == 2:
                self.cloth -= amt_withdrawal
            elif choice == 3:
                self.entertainment -= amt_withdrawal

if __name__ == "__main__":
    try:
        deposit = float(input("请输入存款金额:"))
        food_p = float(input("请输入食品预算的百分比:"))
        cloth_p = float(input("请输入服装预算的百分比:"))
        ent_p = float(input("请输入娱乐预算的百分比:"))
        
        budg = BudgetApp(deposit, food_p, cloth_p, ent_p)
        budg.withdrawal()
    except ValueError as e:
        print(e)

关键改进点

  • 遵循Python命名规范,类名改为大驼峰格式BudgetApp,变量名使用小驼峰
  • 初始化时将百分比转换为实际存款比例金额,匹配用户输入逻辑
  • 添加总预算校验,超过存款时直接抛出明确错误提示
  • 简化重复的取款逻辑,提升代码可读性和维护性
  • 增加输入异常处理,避免非数字输入导致程序崩溃
  • 取款成功后更新对应类别余额,符合实际预算管理逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 01:45:30