To solve this problem, we need to create a Python class that models a basic bank account. This class will handle essential operations such as initializing the account with a balance, depositing funds, withdrawing funds, and displaying the current balance.
Approach
The approach to building the BankAccount class involves the following key steps:
- Initialization: The class will be initialized with an optional initial balance (defaulting to 0.0). We also ensure the initial balance is non-negative to maintain valid account state.
- Deposit: A method to add funds to the account. This method checks if the deposit amount is positive to avoid invalid transactions.
- Withdrawal: A method to subtract funds from the account. This method checks if the withdrawal amount is positive and if there are sufficient funds to complete the transaction.
- Show Balance: A method to display the current balance in a user-friendly currency format.
Solution Code
class BankAccount:
def __init__(self, initial_balance=0.0):
"""Initialize the bank account with an optional initial balance."""
if initial_balance < 0:
raise ValueError("Initial balance cannot be negative.")
self.balance = initial_balance
def deposit(self, amount):
"""Deposit funds into the account."""
if amount <= 0:
print("Deposit amount must be positive.")
return
self.balance += amount
print(f"Deposited ${amount:.2f}. New balance: ${self.balance:.2f}")
def withdraw(self, amount):
"""Withdraw funds from the account."""
if amount <= 0:
print("Withdrawal amount must be positive.")
return
if amount > self.balance:
print("Insufficient funds.")
return
self.balance -= amount
print(f"Withdrew ${amount:.2f}. New balance: ${self.balance:.2f}")
def show_balance(self):
"""Display the current account balance."""
print(f"Your current balance is: ${self.balance:.2f}")
# Example usage
if __name__ == "__main__":
# Create an account with initial balance 100
account = BankAccount(100)
account.show_balance() # Output: Your current balance is: $100.00
# Deposit 50
account.deposit(50) # Output: Deposited $50.00. New balance: $150.00
# Withdraw 30
account.withdraw(30) # Output: Withdrew $30.00. New balance: $120.00
# Try to withdraw more than balance
account.withdraw(200) # Output: Insufficient funds.
# Try to deposit negative amount
account.deposit(-10) # Output: Deposit amount must be positive.
# Show final balance
account.show_balance() # Output: Your current balance is: $120.00
Explanation
- Initialization: The
__init__method sets the initial balance and checks for negative values to ensure valid account setup. - Deposit: The
depositmethod adds funds only if the amount is positive, updating the balance and notifying the user. - Withdrawal: The
withdrawmethod subtracts funds only if the amount is positive and the account has enough balance, otherwise it displays an error message. - Show Balance: The
show_balancemethod formats the balance to two decimal places for currency-like display, making it easy to read.
This class provides a robust foundation for basic bank account operations, ensuring valid transactions and clear user feedback.


作者声明:本文包含人工智能生成内容。