Jul-05-2018, 04:48 PM
(This post was last modified: Jul-05-2018, 04:48 PM by Zombie_Programming.)
This program is supposed to mimic, in a way, a banking program. Essentially it allows the user to login using a 12-digit pre-generated account number and a user-created PIN. If the user doesn't have an account, the user can register with the bank and get an account number. Once the user is logged in, they can make withdrawals, deposits and view a transaction log. It also allows them to log out of the system which will take them back to the login screen. I know the code is probably messy but I would really love feedback on how I can improve on this in the future.
The code is split into three files:
My function library(Called bankAccount):
This is my Account Class file:
Then this is my main file.
Login Screen
The code is split into three files:
My function library(Called bankAccount):
# FUNCTION LIST FOR BANK ACCOUNT SIM V2 import random, datetime, os, time #** GENERATE ACCOUNT NUMBER **# def genAcctNum(): # Generate a random 12-digit account number, convert into string generatedAcctNum = str(random.randint(100000000000, 999999999999)) # Set the location of the acctNum.txt file fileLocation = "C:/Users/bagpi/Desktop/Python Tutorial Files/Personal Projects/Bank Account SIM v2/Login_Info/acctNum.txt" trans = "C:/Users/bagpi/Desktop/Python Tutorial Files/Personal Projects/Bank Account SIM v2/Trans Logs/" # Open the acctNumFile in read mode and read the contents of the file to compare # This will be used to check if the generated acct # is already in the database of acct #'s isGen = False while not(isGen): acctNumFile = open(fileLocation, 'r') acctNum = acctNumFile.readline().strip() # Check to see if file is empty: if acctNum == '': acctNumFile.close() isGen = True else: while acctNum != '': if acctNum == generatedAcctNum: generatedAcctNum = str(random.randint(100000000000, 999999999999)) acctNumFile.close() break else: acctNumFile.close() isGen = True break # Once the file has been searched and the account # is generated, append the # account # to the database. acctNumFile = open(fileLocation, 'a') acctNumFile.write(generatedAcctNum + "\n") acctNumFile.close() # Create trans log file translog = open(trans+"transLog"+generatedAcctNum+".txt", 'a') translog.close() # Return the account number return generatedAcctNum #***********************************************************************************************************************************************# #** GET A UI **# def getMenu(menuNum): # Open file folder for UI, put all files into a list filePre = "C:/Users/bagpi/Desktop/Python Tutorial Files/Personal Projects/Bank Account SIM v2/UI/" fileList = [] for i in range(4): file = open(filePre+"UI"+str(i)+".txt", 'r') fileList.append(file) # 0 = Header, 1 = Login, 2 = User, 3 = Registration text = fileList[menuNum].readline().strip() while text != '': print(text) text = fileList[menuNum].readline().strip() #***********************************************************************************************************************************************# #** GET DOB **# def getDOB(): while True: try: y, m, d = eval(input("Enter your date of birth[yyyy, -m, -d]:")) DOB = datetime.date(y, m, d) break except: continue return DOB #***********************************************************************************************************************************************# #** GET NAME **# def getName(): while True: try: name = input("Enter your full name:") if name.replace(' ', '').isalpha(): break else: pass except: continue return name #***********************************************************************************************************************************************# #** GET SSN **# def getSSN(): while True: try: SSN = input("Enter your SSN[xxxxxxxxx]:") if SSN.isdigit() and len(SSN) == 9: break else: pass except: continue return SSN #***********************************************************************************************************************************************# #** GET BALANCE **# def getBalance(): while True: try: balance = input("Enter an initial balance:$") if float(balance) > 1000: pass else: break except: continue return balance #***********************************************************************************************************************************************# #** GET BALANCE **# def getPIN(): file = "C:/Users/bagpi/Desktop/Python Tutorial Files/Personal Projects/Bank Account SIM v2/Login_Info/PIN.txt" pins = open(file, 'a') while True: try: PIN = input("Create a Personal ID #:") if len(PIN)!=4 and not(PIN.isdigit): pass else: break except: continue pins.write(PIN + '\n') pins.close() return PIN #***********************************************************************************************************************************************# #** LOG DATA INTO FILE **# def logData(): # Ask for data name = getName() DOB = getDOB() SSN = getSSN() PIN = getPIN() balance = getBalance() acctNum = genAcctNum() # Create the path for the file folder logFilePre = "C:/Users/bagpi/Desktop/Python Tutorial Files/Personal Projects/Bank Account SIM v2/Account_Information/" # Create a file with the user's account # acctFile = open(logFilePre+"account"+acctNum+"info.txt", 'w+') # Log data into file in correct order acctFile.write(acctNum+'\n') acctFile.write(PIN+'\n') acctFile.write(name+'\n') acctFile.write(str(DOB)+'\n') acctFile.write(SSN+'\n') acctFile.write(balance+'\n') # Close the file acctFile.close() # Return all of the data variables return name, DOB, SSN, PIN, balance, acctNum #***********************************************************************************************************************************************# #** REGISTRATION **# def registration(): # Clear the screen os.system("CLS") # Print Bank Header getMenu(0) getMenu(3) # Get user Data name, DOB, SSN, PIN, balance, acctNum = logData() # Tell User their acct# and PIN print('\n') print("Do NOT share this information with anyone!") print("ACCOUNT NUMBER:", acctNum) print("PIN:", PIN) #***********************************************************************************************************************************************# #** CHECK LOGIN DATA **# def checkLogin(acctNum, PIN): # Open account numbers and PIN text files acctFile = "C:/Users/bagpi/Desktop/Python Tutorial Files/Personal Projects/Bank Account SIM v2/Login_Info/acctNum.txt" pinFile = "C:/Users/bagpi/Desktop/Python Tutorial Files/Personal Projects/Bank Account SIM v2/Login_Info/PIN.txt" acctNums = open(acctFile, 'r') pins = open(pinFile, 'r') # Read line by line checking if acct num and pin match in the files readAcctNum = acctNums.readline().strip() readPIN = pins.readline().strip() acctList = [] pinList = [] # Get Account Numbers while readAcctNum != '': acctList.append(readAcctNum) readAcctNum= acctNums.readline().strip() # Get PINs while readPIN != '': pinList.append(readPIN) readPIN = pins.readline().strip() # Set a variable to check if valid. Check if acct number matches with PIN isValid = False for i in range(len(acctList)): if acctList[i] == acctNum: if pinList[i] == PIN: isValid = True return isValid #***********************************************************************************************************************************************# #** LOGIN **# def login(): # Set varibles to check for lockout and set lockout times tries = 0 timeWait = 0 lockoutNum = 0 timeoutDone = True # Show login menu getMenu(0) getMenu(1) # Login Loop while True: # Print a blank line print() # Check if the person is currently locked out or not if lockoutNum > 0 and timeoutDone == False: # Set a lockout time based on the equation timeWait = 6 * lockoutNum / 2 # Tell the user that they've tried to enter in information too many times print("You've entered the wrong information too many times!") print("Please wait " + str(timeWait) + " seconds.") # Lockout, prevent from asking for the account # and PIN while timeWait != 0: time.sleep(1) timeWait -= 1 # Timeout is done timeoutDone = True # Clear the screen and take them back to login. os.system("CLS") getMenu(0) getMenu(1) continue # Ask the user for their Acct # userAcctNum = input("Acct #: ") # If they enter register instead, take them to registration portal if userAcctNum == "register": registration() os.system("PAUSE") os.system("CLS") getMenu(1) continue # If they enter quit, quit the program elif userAcctNum == "quit": quit() # Else, ask for their PIN else: userPIN = input("PIN: ") # Check if the user enters quit into PIN if userPIN == 'quit': quit() # If the information is correct, take them to user Main Menu isLogin = checkLogin(userAcctNum, userPIN) if isLogin == True: os.system("CLS") animation(3, "Login Success") os.system("CLS") break # If the information is incorrect, do some things... else: # If the user enters the wrong information 3 times in a row, lock the user out. tries += 1 if tries % 3 == 0: lockoutNum += 1 timeoutDone = False # Tell the user their info was incorrect, clear login screen. os.system("CLS") getMenu(0) print("\nLogin details incorrect! Try Again!\n") getMenu(1) continue # When done, return user information return userAcctNum, userPIN #***********************************************************************************************************************************************# #** UPDATE BALANCE LINE **# def updateBalance(fileName, lineNum, balance): # read the lines in the file, creates a list lines = open(fileName, 'r').readlines() # Replace balance, Line number 5 lines[lineNum] = balance+'\n' # Rewrite file and close out = open(fileName, 'w') out.writelines(lines) out.close() #***********************************************************************************************************************************************# #** USER MENU **# def showUserMenu(name, balance): # Get Menu getMenu(0) print("Welcome back, " + name) print("CURRENT BALANCE: $" + balance) getMenu(2) # MAIN LOOP while True: # Ask user for choice userChoice = input("\nChoice: ") # Return users choice if userChoice == '1': return 'Withdrawal' if userChoice == '2': return 'Deposit' if userChoice == '3': return 'Transaction Log' if userChoice == '0': return 'Logout' if userChoice == 'quit': quit() else: # If option is not valid, clear screen and tell user. os.system("CLS") getMenu(0) print("NOT A VALID OPTION!") print() print("Welcome back, " + name) print("CURRENT BALANCE: $", balance) getMenu(2) continue #***********************************************************************************************************************************************# #** ANIMATION **# def animation(Time, message): # This is used to make the LOGIN SUCCESS look 'prettier' tempTime = 0 while Time > tempTime: dot = message + '' for i in range(3): dot += '.' print(dot) time.sleep(0.3) os.system("CLS") tempTime += 0.5 #***********************************************************************************************************************************************# #** CHECK THE PIN **# def checkPIN(pin): # Set vars to chcek for correct PIN pinCheck = False tries = 0 # Loop while the user has not input 3 incorrect PINs while tries != 3: # Ask for user's PIN userPin = input("Please enter your comformation PIN: ") # If the PIN is correct, pinCheck = True. if userPin == pin: pinCheck = True break else: # Increment tries tries += 1 continue # Will return false unless PIN is correct return pinCheck
This is my Account Class file:
import bankAccount, os from datetime import datetime class Account: def __init__(self, acctNum, pin): # Initialize acct# and pin self.__acctNum = acctNum self.__pin = pin # Open account file file = "C:/Users/bagpi/Desktop/Python Tutorial Files/Personal Projects/Bank Account SIM v2/Account_Information/account"+self.__acctNum+"info.txt" acctFile = open(file, 'r') # Set account information (Skip first two lines and last line) acctFile.readline() acctFile.readline() # Set account information self.__name = acctFile.readline().strip() self.__DOB = acctFile.readline().strip() self.__SSN = acctFile.readline().strip() self.__balance = acctFile.readline().strip() # Skip last line acctFile.readline().strip() # Close the file acctFile.close() def makeWithdrawal(self): # Clear the screen, show the bank header os.system("CLS") bankAccount.getMenu(0) # File location file = "C:/Users/bagpi/Desktop/Python Tutorial Files/Personal Projects/Bank Account SIM v2/Account_Information/account"+self.__acctNum+"info.txt" transFile = "C:/Users/bagpi/Desktop/Python Tutorial Files/Personal Projects/Bank Account SIM v2/Trans Logs/transLog" # Print withdrawal UI print("WITHDRAWAL") print("----------") print("Current Balance: $" + self.__balance+'\n') # Ask user to enter an amount to withdrawal while True: try: amount = float(input("Enter an amount to withdrawal: $")) if amount > float(self.__balance): pass else: break except: print("Please enter a valid amount!") continue # PIN Comformation, this will loop 3 times(Or until the user enters the correct PIN) pinCom = bankAccount.checkPIN(self.__pin) if pinCom == True: # Update the balance and input into info file self.__balance = str(float(self.__balance) - amount) bankAccount.updateBalance(file, 5, self.__balance) print("\nTransaction Success!") os.system("PAUSE") else: # Run only if the PIN was incorrect print("\nTransaction Failed. PIN couldn't be confirmed") os.system("PAUSE") # Write to trans log file for the account initAmount = float(self.__balance)+amount transLog = open(transFile+self.__acctNum+".txt", 'a') transLog.write('W\n'+str(initAmount)+"\n"+str(amount)+"\n"+str(datetime.now().replace(microsecond=0))+"\n") transLog.close() def makeDeposit(self): # Clear the screen os.system("CLS") # Bank Header bankAccount.getMenu(0) # File Location file = "C:/Users/bagpi/Desktop/Python Tutorial Files/Personal Projects/Bank Account SIM v2/Account_Information/account"+self.__acctNum+"info.txt" transFile = "C:/Users/bagpi/Desktop/Python Tutorial Files/Personal Projects/Bank Account SIM v2/Trans Logs/transLog" # Print Deposit UI print("DEPOSIT") print("-------") print("Current Balance: $" + self.__balance) # Ask user to enter an amount to deposit while True: try: amount = float(input("Enter an amount to Deposit: $")) if amount > 1000 and self.__name != "ADMIN": pass else: break except: print("Please enter a valid amount under $1000") continue # PIN Comformation pinCom = bankAccount.checkPIN(self.__pin) if pinCom == True: # Update the balance and input into info file self.__balance = str(float(self.__balance)+amount) bankAccount.updateBalance(file, 5, self.__balance) print("\nTransaction Success!") os.system("PAUSE") else: print("\nTransaction Failed. PIN couldn't be confirmed") os.system("PAUSE") # Write to trans log file for the account initAmount = float(self.__balance)-amount transLog = open(transFile+self.__acctNum+".txt", 'a') transLog.write('D\n'+str(initAmount)+"\n"+str(amount)+"\n"+str(datetime.now().replace(microsecond=0))+"\n") transLog.close() def getTransLog(self): os.system("CLS") # Open the transLog file for the current user transFolder = "C:/Users/bagpi/Desktop/Python Tutorial Files/Personal Projects/Bank Account SIM v2/Trans Logs/transLog" transFile = transFolder + self.__acctNum + ".txt" transLog = open(transFile, 'r') # Show transaction log header: print("Transaction Type Date Transaction Amount Balance After Transaction") print("--------------------------------------------------------------------------------------------------------------") # Read the transCode in the file transCode = transLog.readline().strip() # If transCode is blank, EOF is reached while transCode != '': # Get the balance before transaction, transaction amount, and date of transaction initBalance = float(transLog.readline().strip()) transAmount = float(transLog.readline().strip()) transDate = transLog.readline().strip() # Output data according to transaction code. if transCode == 'D': print(format("Deposit", '<26s'), format(transDate, '<30s'), format(transAmount, '<26.2f'), format(initBalance+transAmount, '<15.2f')) if transCode == 'W': print(format("Withdrawal", '<26s'), format(transDate, '<30s'), format(transAmount, '<26.2f'), format(initBalance-transAmount, '<15.2f')) # Read next transaction code transCode = transLog.readline().strip() # Print footer print("--------------------------------------------------------------------------------------------------------------") print("CURRENT BALANCE: $"+self.__balance) # Wait for user os.system("PAUSE") def getName(self): return self.__name def getDOB(self): return self.__DOB def getSSN(self): return self.__SSN def getBalance(self): return self.__balance
Then this is my main file.
import bankAccount, datetime, os from Account import Account def main(): while True: acctNum, PIN = bankAccount.login() # Create User Account object userAccount = Account(acctNum, PIN) while True: os.system("CLS") userMenu = bankAccount.showUserMenu(userAccount.getName(), userAccount.getBalance()) if userMenu == 'Deposit': userAccount.makeDeposit() if userMenu == 'Withdrawal': userAccount.makeWithdrawal() if userMenu == 'Transaction Log': userAccount.getTransLog() if userMenu == 'Logout': os.system("cls") break main()Here's the different output screens:
Login Screen
Output:Welcome to Bank Account SIM v2 Made by: Dillon
***************************************************************
LOGIN PORTAL
************
Welcome to Bank SIM v2. Please log in down below.
If you are not registered, type 'register' in the ACCT#
field. Type 'quit' at any time to quit the program.
Acct #:
User Main MenuOutput:Welcome to Bank Account SIM v2 Made by: Dillon
***************************************************************
Welcome back, ADMIN
CURRENT BALANCE: $5750.0
Choose an option below
+---------------------+
|1. WITHDRAWAL |
|2. DEPOSIT |
|3. TRANSACTION LOG |
+---------------------+
|0. LOG OUT |
+---------------------+
Type 'quit' at any time to quit the program.
Choice:
Withdrawal MenuOutput:Welcome to Bank Account SIM v2 Made by: Dillon
***************************************************************
WITHDRAWAL
----------
Current Balance: $5750.0
Enter an amount to withdrawal: $
Transaction LogOutput:Transaction Type Date Transaction Amount Balance After Transaction
--------------------------------------------------------------------------------------------------------------
Withdrawal 2018-07-04 23:26:35 100.00 9250.00
Deposit 2018-07-04 23:27:00 2000.00 11250.00
Withdrawal 2018-07-04 23:27:04 100.00 11150.00
Withdrawal 2018-07-04 23:27:12 3000.00 8150.00
Withdrawal 2018-07-04 23:27:21 1000.00 7150.00
Deposit 2018-07-04 23:27:26 100.00 7250.00
Deposit 2018-07-04 23:27:32 500.00 7750.00
Withdrawal 2018-07-04 23:27:36 1000.00 6750.00
Withdrawal 2018-07-05 10:13:16 1000.00 5750.00
Withdrawal 2018-07-05 11:45:19 0.00 5750.00
--------------------------------------------------------------------------------------------------------------
CURRENT BALANCE: $5750.0
Registration PortalOutput:Welcome to Bank Account SIM v2 Made by: Dillon
***************************************************************
REGISTRATION PORTAL
-------------------
Enter your full name:John Smith
Enter your date of birth[yyyy, -m, -d]:1987,2,21
Enter your SSN[xxxxxxxxx]:123456789
Create a Personal ID #:1234
Enter an initial balance:$1000
Do NOT share this information with anyone!
ACCOUNT NUMBER: 462140927428
PIN: 1234
It may get confusing; if you have any questions about the code please just ask. I will be sure to be active on this thread. I really can't wait to hear the feedback.