Day 67 - OOP ATM Simulator - Part 3: Building Create and List Accounts Methods

In this episode, we will add methods for creating accounts and also listing accounts, and we will do a little debugging as we go.

Starter Code

import pickle, os

class bankAccount:
    def __init__(self, strN):
        self.strName = strN
        self.flBal = 0

    def getBalance(self):
        return self.flBal

    def getName(self):
        return self.strName

    def doDeposit(self):
        strDeposit = input("How much would you like to deposit?").strip()
        strDepositCheck = strDeposit.replace(".", "", 1)
        if strDepositCheck.isnumeric():
            flDep = float(strDeposit)
            self.flBal += flDep
            print(f"You have deposited {flDep} in {self.strName}.\n")
        else:
            print("Please enter a valid decimal number.\n")

    def doWithdrawal(self):
        strWith = input("How much would you like to withdraw?").strip()
        strWithCheck = strWith.replace(".", "", 1)
        if strWithCheck.isnumeric():
            flWith = float(strWith)
            if self.flBal >= flWith:
                self.flBal -= flWith
                print(f"You have withdrawn {flWith:.2f} from {self.strName}.\n")
            else:
                print("You don't have enough money in your account.")
        else:
            print("Please enter a valid decimal number.\n")

class savingsAccount(bankAccount):
    def __init__(self, strN):
        super().__init__(strN)

    def __str__(self):
        return f"{self.strName}".ljust(25,".")+"Savings".ljust(10,".")+f"${self.flBal:.2f}".rjust(25, ".")

class checkingAccount(bankAccount):
    def __init__(self, strN):
        super().__init__(strN)
        self.intCheckNo = 1000

    def __str__(self):
        return f"{self.strName}".ljust(25,".")+"Checking".ljust(10,".")+f"${self.flBal:.2f}".rjust(25, ".")


    def writeCheck(self):
        strWith = input("How much is the check for? ").strip()
        strWithCheck = strWith.replace(".", "", 1)
        if strWithCheck.isnumeric():
            flWith = float(strWith)
            if self.flBal >= flWith:
                self.flBal -= flWith
                print(f"You have written check number {self.intCheckNo} for ${flWith:.2f} from {self.strName}.\n")
                self.intCheckNo += 1
            else:
                print("You don't have enough money in your account.")
        else:
            print("Please enter a valid decimal number.\n")

class accountList:
    def __init__(self):
        while True:
            strLoad = input("Do you want to (o)pen an existing list, or create a (n)ew list? ").strip().lower()
            if strLoad == "o":
                break
            elif strLoad == "n":
                break
            else:
                print("Please choose 'o' or 'n'.")

        if strLoad == "o":
            strPrefix = "atmdata_"
            files = os.listdir(".")
            intIndex = 0
            liFiles = []
            for file in files:
                if os.path.isfile(file) and file.startswith(strPrefix):
                    print(f"{intIndex}. ".ljust(5), end="")
                    strFileName = file.replace(strPrefix, "")
                    strFileName = strFileName.replace(".txt", "")
                    liFiles.append(file)
                    print(strFileName)
                    intIndex += 1

            while True:
                strFile = input("Enter the number of the file to open: ")
                if strFile.isnumeric():
                    intFile = int(strFile)
                    if intFile <= intIndex:
                        file = open(liFiles[intFile], "rb")
                        self.liAccounts = pickle.load(file)
                        file.close()
                        break
                    else:
                        print("You must choose a file that exists.")
                else:
                    print("You must choose a number from the list above.")



        elif strLoad == "n":
            while True:
                print("\nYou chose to create a new Account List.\n")
                strName = input("What is the name of the account list? (letters only, no spaces")
                strName = strName.replace(" ","")
                if strName.isalpha():
                    self.strDataFile = strName
                    strFileStr = f"atmdata_{strName}.txt"
                    self.liAccounts = []
                    file = open(strFileStr, "wb")
                    pickle.dump(self.liAccounts, file)
                    file.close()
                    break
                else:
                    print("\nYou must enter a valid file name.")

        if len(self.liAccounts) == 0:
            self.createAccount()

    def createAccount(self):
        pass

myAccounts = accountList()

Finished Code

import pickle, os

class bankAccount:
    def __init__(self, strN):
        self.strName = strN
        self.flBal = 0

    def getBalance(self):
        return self.flBal

    def getName(self):
        return self.strName

    def doDeposit(self):
        strDeposit = input("How much would you like to deposit?").strip()
        strDepositCheck = strDeposit.replace(".", "", 1)
        if strDepositCheck.isnumeric():
            flDep = float(strDeposit)
            self.flBal += flDep
            print(f"You have deposited {flDep} in {self.strName}.\n")
        else:
            print("Please enter a valid decimal number.\n")

    def doWithdrawal(self):
        strWith = input("How much would you like to withdraw?").strip()
        strWithCheck = strWith.replace(".", "", 1)
        if strWithCheck.isnumeric():
            flWith = float(strWith)
            if self.flBal >= flWith:
                self.flBal -= flWith
                print(f"You have withdrawn {flWith:.2f} from {self.strName}.\n")
            else:
                print("You don't have enough money in your account.")
        else:
            print("Please enter a valid decimal number.\n")

class savingsAccount(bankAccount):
    def __init__(self, strN):
        super().__init__(strN)

    def __str__(self):
        return f"{self.strName}".ljust(25,".")+"Savings".ljust(10,".")+f"${self.flBal:.2f}".rjust(25, ".")

class checkingAccount(bankAccount):
    def __init__(self, strN):
        super().__init__(strN)
        self.intCheckNo = 1000

    def __str__(self):
        return f"{self.strName}".ljust(25,".")+"Checking".ljust(10,".")+f"${self.flBal:.2f}".rjust(25, ".")


    def writeCheck(self):
        strWith = input("How much is the check for? ").strip()
        strWithCheck = strWith.replace(".", "", 1)
        if strWithCheck.isnumeric():
            flWith = float(strWith)
            if self.flBal >= flWith:
                self.flBal -= flWith
                print(f"You have written check number {self.intCheckNo} for ${flWith:.2f} from {self.strName}.\n")
                self.intCheckNo += 1
            else:
                print("You don't have enough money in your account.")
        else:
            print("Please enter a valid decimal number.\n")

class accountList:
    def __init__(self):
        while True:
            strLoad = input("Do you want to (o)pen an existing list, or create a (n)ew list? ").strip().lower()
            if strLoad == "o":
                break
            elif strLoad == "n":
                break
            else:
                print("Please choose 'o' or 'n'.")

        if strLoad == "o":
            strPrefix = "atmdata_"
            files = os.listdir(".")
            intIndex = 0
            liFiles = []
            for file in files:
                if os.path.isfile(file) and file.startswith(strPrefix):
                    print(f"{intIndex}. ".ljust(5), end="")
                    strFileName = file.replace(strPrefix, "")
                    strFileName = strFileName.replace(".txt", "")
                    liFiles.append(file)
                    print(strFileName)
                    intIndex += 1

            while True:
                strFile = input("Enter the number of the file to open: ")
                if strFile.isnumeric():
                    intFile = int(strFile)
                    if intFile <= intIndex:
                        strFN = liFiles[intFile]
                        strFN = strFN.replace("atmdata_", "")
                        strFN = strFN.replace(".txt", "")
                        self.strDataFile = strFN
                        file = open(liFiles[intFile], "rb")
                        self.liAccounts = pickle.load(file)
                        file.close()
                        break
                    else:
                        print("You must choose a file that exists.")
                else:
                    print("You must choose a number from the list above.")



        elif strLoad == "n":
            while True:
                print("\nYou chose to create a new Account List.\n")
                strName = input("What is the name of the account list? (letters only, no spaces")
                strName = strName.replace(" ","")
                if strName.isalpha():
                    self.strDataFile = strName
                    strFileStr = f"atmdata_{strName}.txt"
                    self.liAccounts = []
                    file = open(strFileStr, "wb")
                    pickle.dump(self.liAccounts, file)
                    file.close()
                    break
                else:
                    print("\nYou must enter a valid file name.")

        if len(self.liAccounts) == 0:
            print("You don't have any accounts in this data. Let's create one now.")
            self.createAccount()

    def saveData(self):
        strFileStr = f"atmdata_{self.strDataFile}.txt"
        file = open(strFileStr, "wb")
        pickle.dump(self.liAccounts, file)
        file.close()

    def createAccount(self):
        while True:
            strType = input("(c)hecking or (s)avings account?").strip().lower()
            if strType == "c" or strType == "s":
                break
            else:
                print("You must select 'c' or 's'.")

        while True:
            print("Choose an account name using only letters and spaces.")
            strN = input("What is the account name?")
            boolValid = True
            for strLetter in strN:
                if strLetter == " " or strLetter.isalpha():
                    pass
                else:
                    boolValid = False

            if boolValid == True:
                break
            else:
                print("Please use only letters and spaces in the account name.")

        if (strType == "c"):
            self.liAccounts.append(checkingAccount(strN))
            print(f"Your checking account {strN} has been created.\n")
        else:
            self.liAccounts.append(savingsAccount(strN))
            print(f"Your savings account {strN} has been created.\n")

        self.saveData()

    def listAccounts(self):
        for account in self.liAccounts:
            print(account)



myAccounts = accountList()
myAccounts.createAccount()
myAccounts.listAccounts()