Removal of error from this small program banking management system using file handling and pickle module

26 Views Asked by At

Removal of errors from this small program banking management system using file handling and pickle module. The error as stated, it contains some errors in choice number 2. Please check and solve it as soon as possible as I require it for a computer science project for school. Error:error Code:

`import pickle

#Function to create welcome header
def print_welcome_header():
    print("************************************************************")
    print("==========     WELCOME TO OUR BANKING SYSTEM    ============")
    print("************************************************************")

# Function to create menu options
def print_menu_options():
    print("==========            1. Create Account         ============")
    print("==========            2. Check Balance          ============")
    print("==========            3. Display All Accounts   ============")
    print("==========            4. Deposit Money          ============")
    print("==========            5. Withdraw Money         ============")
    print("==========            6. Exit                   ============")

# Function to display menu
def print_menu():
    print_welcome_header()
    print_menu_options()
    print("************************************************************")

def create_account(account_number, name, balance, pin):
    """
    Create a new account and store the account details in a pickle file.

    Parameters:
    - account_number (str): The account number for the new account.
    - name (str): The name associated with the new account.
    - balance (float): The initial balance for the new account.
    - pin (int): The 4-digit Personal Identification Number (PIN) for the new account.

    Returns:
    None
    """
    # Check if the PIN is a 4-digit number
    if not (isinstance(pin, int) and 1000 <= pin <= 9999):
        print("Error: PIN must be a 4-digit number.")
        return

    # Create a dictionary with account details
    account_data = {
        "AccountNumber": account_number,
        "Name": name,
        "Balance": balance,
        "PIN": pin
    }

    # Open the pickle file in binary mode and dump the account data
    with open("accounts_pickle.pkl", "ab") as pickle_file:
        pickle.dump(account_data, pickle_file)

def check_balance(account_number, pin):
    """
    Check the balance for a specific account and PIN.

    Parameters:
    - account_number (str): The account number for which to check the balance.
    - pin (int): The 4-digit Personal Identification Number (PIN) associated with the account.

    Returns:
    float: The balance of the specified account if found, otherwise None.
    """
    # Open the pickle file in binary mode and check the balance for the given account and PIN
    with open("accounts_pickle.pkl", "rb") as pickle_file:
        try:
            while True:
                account_data = pickle.load(pickle_file)
                if account_data["AccountNumber"] == account_number and account_data["PIN"] == pin:
                    return account_data["Balance"]
        except EOFError:
            pass

def display_accounts():
    """
    Display details of all accounts stored in the pickle file.

    Parameters:
    None

    Returns:
    None
    """
    # Open the pickle file in binary mode and display all accounts
    print("\nAll Accounts:")
    with open("accounts_pickle.pkl", "rb") as pickle_file:
        try:
            while True:
                account_data = pickle.load(pickle_file)
                print(account_data)
        except EOFError:
            pass

def deposit_money(account_number, amount, pin):
    """
    Deposit money into a specific account.

    Parameters:
    - account_number (str): The account number for which to deposit money.
    - amount (float): The amount to deposit.
    - pin (int): The 4-digit Personal Identification Number (PIN) associated with the account.

    Returns:
    None
    """
    # Open the pickle file in binary mode and update the balance for the given account and PIN after deposit
    with open("accounts_pickle.pkl", "rb") as pickle_file:
        accounts = []
        try:
            while True:
                account_data = pickle.load(pickle_file)
                if account_data["AccountNumber"] == account_number and account_data["PIN"] == pin:
                    account_data["Balance"] += amount
                accounts.append(account_data)
        except EOFError:
            pass

    # Open the pickle file in binary mode and dump the updated account data
    with open("accounts_pickle.pkl", "wb") as pickle_file:
        for account_data in accounts:
            pickle.dump(account_data, pickle_file)

def withdraw_money(account_number, amount, pin):
    """
    Withdraw money from a specific account.

    Parameters:
    - account_number (str): The account number for which to withdraw money.
    - amount (float): The amount to withdraw.
    - pin (int): The 4-digit Personal Identification Number (PIN) associated with the account.

    Returns:
    None
    """
    # Open the pickle file in binary mode and update the balance for the given account and PIN after withdrawal
    with open("accounts_pickle.pkl", "rb") as pickle_file:
        accounts = []
        try:
            while True:
                account_data = pickle.load(pickle_file)
                if account_data["AccountNumber"] == account_number and account_data["PIN"] == pin:
                    if account_data["Balance"] >= amount:
                        account_data["Balance"] -= amount
                    else:
                        print("Insufficient funds.")
                accounts.append(account_data)
        except EOFError:
            pass

    # Open the pickle file in binary mode and dump the updated account data
    with open("accounts_pickle.pkl", "wb") as pickle_file:
        for account_data in accounts:
            pickle.dump(account_data, pickle_file)

def main():
    while True:
        print_menu()

        choice = input("Enter your choice (1-6): ")

        if choice == "1":
            # Input account details and PIN from the user
            account_number = input("Enter Account Number: ")
            name = input("Enter Name: ")
            balance = float(input("Enter Initial Balance: "))
            while True:
                try:
                    pin = int(input("Enter 4-digit PIN: "))
                    if 1000 <= pin <= 9999:
                        break
                    else:
                        print("Error: PIN must be a 4-digit number.")
                except ValueError:
                    print("Error: PIN must be a numeric value.")
            
            # Call the function to create an account
            create_account(account_number, name, balance, pin)
            print("Account created successfully.")

        elif choice == "2":
            # Input account number and PIN from the user
            account_number = input("Enter Account Number: ")
            pin = input("Enter PIN: ")
            
            # Call the function to check the balance
            balance = check_balance(account_number, pin)
            if balance is not None:
                print(f"Balance for Account {account_number}: ${balance}")
            else:
                print("Account not found or PIN is incorrect.")

        elif choice == "3":
            # Call the function to display all accounts
            display_accounts()

        elif choice == "4":
            # Input account number, PIN, and deposit amount from the user
            account_number = input("Enter Account Number: ")
            pin = input("Enter PIN: ")
            amount = float(input("Enter Deposit Amount: "))
            
            # Call the function to deposit money
            deposit_money(account_number, amount, pin)
            print("Deposit successful.")

        elif choice == "5":
            # Input account number, PIN, and withdrawal amount from the user
            account_number = input("Enter Account Number: ")
            pin = input("Enter PIN: ")
            amount = float(input("Enter Withdrawal Amount: "))
            
            # Call the function to withdraw money
            withdraw_money(account_number, amount, pin)
            print("Withdrawal successful.")

        elif choice == "6":
            print("Exiting program. Goodbye!")
            with open("accounts_pickle.pkl", "ab") as pickle_file:
                pickle_file.close()
            break

        else:
            print("Invalid choice. Please enter a number between 1 and 6.")

if __name__ == "__main__":
    main()

`

I was trying check balance of accounts in bank_accounts.pkl through 2nd choice of program menu but result was not as expected it was the else line that was printed as output.

0

There are 0 best solutions below