
Today I continued my banking system exercise from yesterday. I admit I had to use a lot of ChatGPT (and started using GitHub Copilot) to build this and it sort of grew over my head, even tho I was able to make it work.
Doesn’t feel like I mastered classes yet, so I’ll probably do some smaller exercise with them in the coming days. Suggestions would always be welcome :)
Anyways here is my working banking system:
"""Exercise: Simple Banking System 2 - This is a continuation of the previous days exercise.Create a basic banking system.Allow users to create a new account, deposit money, withdraw money, and check their balance. With a master password one can also check all balances.Account details are stored in JSON file, so they are continuous even after the program is closed.Use classes to represent users and accounts."""importjsonimportlogginglogging.basicConfig(level=logging.INFO)classAccount:def__init__(self,account_id,holder_name,initial_balance=0):self.account_id=account_idself.holder_name=holder_nameself.balance=initial_balancedefdeposit(self,amount):ifamount>0:self.balance+=amountlogging.info(f"Deposited{amount}. New balance of{self.holder_name}:{self.balance}")else:logging.warning("Invalid deposit amount.")defwithdraw(self,amount):if0<amount<=self.balance:self.balance-=amountlogging.info(f"Withdrew{amount}. New balance of{self.holder_name}:{self.balance}")else:logging.warning("Invalid withdrawal amount or insufficient funds.")defget_balance(self):returnself.balanceclassBank:def__init__(self):self.accounts={}self.used_ids=set()self.load_accounts()defsave_accounts(self):ifnotself.accounts:logging.warning("No accounts to save.")returnwithopen('accounts.json','w')asfile:data={account_id:{'holder_name':account.holder_name,'balance':account.balance}foraccount_id,accountinself.accounts.items()}json.dump(data,file)logging.debug(f"Saved accounts:{data}")defload_accounts(self):try:withopen('accounts.json','r')asfile:data=json.load(file)ifnotdata:logging.warning("JSON file is empty.")returnforaccount_id,account_infoindata.items():account_id=int(account_id)# Convert to int since JSON keys are always stringsself.accounts[account_id]=Account(account_id,account_info['holder_name'],account_info['balance'])self.used_ids.add(account_id)logging.debug(f"Loaded accounts:{self.accounts.keys()}")logging.debug(f"Used IDs after loading:{self.used_ids}")except(FileNotFoundError,json.JSONDecodeError)ase:logging.warning(f"Error loading account data:{e}")logging.info("No existing account data found or file is empty. Starting fresh.")defcreate_account(self,holder_name,initial_balance=0):account_id=self.generate_account_id()new_account=Account(account_id,holder_name,initial_balance)self.accounts[account_id]=new_accountself.used_ids.add(account_id)logging.info(f"Account created with ID:{account_id}")returnaccount_iddefgenerate_account_id(self):# Find the lowest unused IDcurrent_id=1whilecurrent_idinself.used_ids:current_id+=1returncurrent_iddefget_account(self,account_id):returnself.accounts.get(account_id,None)defmain():bank=Bank()try:whileTrue:user_input=input('What would you like to do? Options: n = new account, d = deposit money, w = withdraw money, c = check balance, l = list all accounts, e = exit\n')ifuser_input=='n':holder_name=input('Enter your name:')initial_balance=float(input('Enter initial deposit:'))account_id=bank.create_account(holder_name,initial_balance)bank.save_accounts()elifuser_input=='d'oruser_input=='w'oruser_input=='c':try:whileTrue:account_id=int(input('Enter account ID:'))ifaccount_idinbank.used_ids:breakelse:logging.warning("Invalid account ID.")account=bank.get_account(account_id)ifuser_input=='d':amount=float(input('Enter deposit amount:'))account.deposit(amount)bank.save_accounts()elifuser_input=='w':amount=float(input('Enter withdrawal amount:'))account.withdraw(amount)bank.save_accounts()elifuser_input=='c':print(f"Current balance:{account.get_balance()}")exceptValueError:logging.warning("Invalid account ID.")elifuser_input=='l':master_password=input('Enter master password:')ifmaster_password=='42':ifnotbank.accounts:# Check if the bank's accounts dictionary is emptyprint("No accounts.")else:print("Accounts:")foraccount_id,accountinbank.accounts.items():print(f"{account_id}:{account.holder_name} -{account.balance}")else:logging.warning("Invalid master password.")elifuser_input=='e':breakelse:logging.info("Invalid option selected.")exceptKeyboardInterrupt:logging.error('KeyboardInterrupt')exceptValueError:logging.error("Invalid input. Please enter a number.")logging.debug('main() end')if__name__=='__main__':main()
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse