1
\$\begingroup\$

Simple object-oriented, money management code where a user can deposit money in, withdraw from, show, and exit the balance.

class BankAccuount:
    def __init__(self, name):
        self.name = name
        self.balance = 0
        print('Hello! Welcome to the Deposit and Withdrawal Machine {}!'.format(self.name))

    def deposit(self):
        '''adds money to balance'''
        amount = float(input('\nEnter amount to be deposited >  '))
        self.balance += amount
        print(f'Amount deposited: {amount}')
        self.display()

    def withdrawal(self):
        '''subtracts money from balance if funds are sufficient'''
        amount = float(input('\nEnter amount to be withdrawn >  '))

        if amount > self.balance:
            print('Insufficient balance')
        else:
            self.balance -= amount
            print('Amount withdrawn:', amount)

        self.display()

    def display(self):
        print(f'\nNet Available Balance is {self.balance}')


whats_your_name = input('What is your name?  ')
consumer = BankAccuount(whats_your_name)

while True:
action = input('\nWould you like to deposit (D), withdraw (W), show balance (S), or exit (E)?  ').upper()

  if action in 'DW':
        while True:
            try:
                if action == 'D':
                    consumer.deposit()
                elif action == 'W':
                    consumer.withdrawal()
                break
            except ValueError:
                print('Use numbers please')
    elif action == 'S':
        consumer.display()
    else:
        print(f'Thank you for your visit {whats_your_name}!')
        break
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Docstring

I see that you had some docstrings for some of your methods. But I didn't see any for your BankAccount class, or for the module. You should include these as well.

Bank Structure

You take input within the deposit and withdraw methods inside the class. These methods should only have one function: adding and subtracting money from the account itself. You should handle user input outside the class.

Containment

Right now, all of your user input code is handled in the global scope of the program. This code should be defined to a function, called from a main guard (will get into that later). This will allow you to structure your code better, and separate your code into chunks as needed. It also lets you see the big picture of your program better.

Consistency

I see you using "".format() and f"". You should stick to one, as they both do the same thing. Personally, I like to use f"" exclusively.

Main Guard

As mentioned above, the code outside of your class should be contained in a function called from a main guard, or in the main guard itself.

Main Guard:

if __name__ == '__main__':
    ... code stuff here ...

Having a main guard clause in a module allows you to both run code in the module directly and also use procedures and classes in the module from other modules. Without the main guard clause, the code to start your script would get run when the module is imported.

Type Hints

Using type hints allows you to see what kinds of variables are to be passed to methods, and what methods return what type of variable. I added some to your class methods, take a look and see how you like them. They can be really helpful.

Updated Code

"""
Module Docstring (a description of your program goes here)
"""
class BankAccount:
    """
    BankAccount Class
    """
    def __init__(self, name: str):
        self.name = name
        self.balance = 0

    def deposit(self, amount: float) -> bool:
        '''adds money to balance'''
        if amount > 0:
            self.balance += amount
            return True
        return False

    def withdraw(self, amount: float) -> bool:
        '''subtracts money from balance if funds are sufficient'''
        if amount > self.balance or amount < 0:
            return False
        self.balance -= amount
        return True

    def display_balance(self):
        """ displays current account balance """
        print(f'\nNet Available Balance is ${self.balance}')

def interface():
    """
    Interface for interacting with the bank account
    """
    print(f'Hello! Welcome to the Deposit and Withdrawal Machine {name}!')
    while True:
        action = input('\nWould you like to deposit (D), withdraw (W), show balance (S), or exit (E)? ').upper()

        if action in "DWSE":
            if action == "D":
                try:
                    deposit_amount = float(input("How much would you like to deposit: "))
                    if not account.deposit(deposit_amount):
                        print("Please enter a positive number!")
                    else:
                        print(f"Successfully deposited {deposit_amount} into your account.")
                except ValueError:
                    print("Please enter a positive number.")
            if action == "W":
                try:
                    withdraw_amount = float(input("How much would you like to withdraw: "))
                    if not account.withdraw(withdraw_amount):
                        print("You do not have enough money to withdraw.")
                    else:
                        print(f"Successfully withdraw {withdraw_amount} from your account.")
                except ValueError:
                    print("Please enter a positive number.")
            if action == "S":
                account.display_balance()
            if action == "E":
                break

if __name__ == '__main__':
    name = input('What is your name? ')
    account = BankAccount(name)
    interface()
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.