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

Python银行账户类代码问题:换行输出与None值消除求助

代码修复方案

你的代码主要有几个核心问题,对应修复方法如下:

问题根源

  1. 账户操作方法(取款/存款/查余额)内部直接打印结果,同时调用方法时又用print拼接名称和方法返回值,导致内容分行输出;而且方法没有return语句,默认返回None,所以最终会额外打印None。
  2. 使用全局变量Amount1、Amount2传递金额,不符合面向对象封装原则,容易引发逻辑混乱。
  3. 取款方法的逻辑遗漏了“金额等于余额”的情况,而且没有实际更新账户余额(原来的代码只是计算了数值,但账户的balance属性没变化)。

修复步骤

1. 让方法返回结果,而非内部打印

把方法里的print改成return,这样外部调用时可以拿到结果,再统一拼接账户名称打印。

2. 将金额作为方法参数传入

把取款/存款金额作为参数传给对应方法,替代全局变量,保证每个账户的操作独立。

3. 完善逻辑并更新账户余额

取款时要更新self.balance,存款同理;同时补充金额等于余额的判断逻辑。

4. 遵循Python命名规范

方法名改用小写加下划线(比如withdraw而非Withdraw),符合PEP8规范。

修正后的完整代码

class Account:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance

    def withdraw(self, amount):
        if amount > self.balance:
            return "You have exceeded your balance."
        # 处理金额小于等于余额的情况
        self.balance -= amount
        return self.balance

    def deposit(self, amount):
        self.balance += amount
        return self.balance

    def check_balance(self):
        return self.balance


account1 = Account("Barbara", 500.00)   
account2 = Account("Joe", 150.00)
account3 = Account("Frank", 20.00)

action = input("What would you like to do; check balance(c), deposit(d), or withdraw(w)? ")
if action == "w": 
    amount = float(input("What amount would you like to withdraw? "))
    print(f"{account1.name}: {account1.withdraw(amount)}")
    print(f"{account2.name}: {account2.withdraw(amount)}")
    print(f"{account3.name}: {account3.withdraw(amount)}")
elif action == "d":
    amount = float(input("What amount would you like to deposit? "))
    print(f"{account1.name}: {account1.deposit(amount)}")
    print(f"{account2.name}: {account2.deposit(amount)}")
    print(f"{account3.name}: {account3.deposit(amount)}")
elif action == "c":
    print(f"{account1.name}: {account1.check_balance()}")
    print(f"{account2.name}: {account2.check_balance()}")
    print(f"{account3.name}: {account3.check_balance()}")

额外说明

  • 用float而非int处理金额,避免无法处理小数的情况。
  • 使用f-string拼接字符串,比+更简洁易读。
  • 用elif替代多个独立if,逻辑更严谨。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:25:20