ATM Account Homework (Classes, Textfiles, Objects) - python

I am completely lost. Our homework assignment is to:
Create an ATM Program that asks a user for their name and pin
Program will loop through asking user if they want to check balance, withdraw, deposit, or exit. You exit the loop when user selects exit. The initial balance is $10,000
Create a text file that records all transactions. First 2 lines of the file should be the User's name and Pin
Create a class called which includes the init and str functions to display info from the user(deposit, check balance, withdraw)
Program needs to read from the file and create an object. The fields for the object are the name, pin, and balance.
6.If the pin number and the name they provide to not match the name and pin number for the BAcc object the program will end. Otherwise you can proceeded to make as many transactions as you want updating the file
7.Errors must by handled using try: blocks! This includes both invalid data entry and insufficient funds on a withdraw.
This is the code I have right now, it doesn't do much but I just need a way to connect it.
accountfile=open("ATMACC.txt", "a")
name=input("What is your name? ")
pin=input("What is your Pin #? ")
accountfile.write("Name: " + name + "\n" + "PIN: " + pin + "\n")
USER_BALANCE = 10000
class BankAcc(object):
def __init__(self,name,pin,balance):
name = self.name
pin = self.pin
10000 = self.balance
def __str__(self):
return "Bank Account with Balance {}".format(self.name,self.balance)
def checkbalance(self):
print(self)
def deposit(self,amount):
self.amount += amount
def withdraw(self,amount):
if self.balance > amount:
self.balance -= amount
else:
raise ValueError
while True:
answer=input("Would you like to deposit, withdraw, check balance, or exit? ")
if answer=="deposit" or answer== "Deposit":
x= input("How much would you like to deposit? ")
USER_BALANCE += float(x)
print ("Your new balance is: $" + str(USER_BALANCE))
accountfile.write("\n" + "Deposit of $" + x + "." + " " + "Current balance is $" + str(USER_BALANCE))
continue
elif answer== "withdraw" or answer== "Withdraw":
y= input("How much would you like to withdraw? ")
if float (y)<=USER_BALANCE:
USER_BALANCE -= float(y)
print ("Your new balance is: $" + str(USER_BALANCE))
accountfile.write("\n" + "Withdraw of $" + y + "." + " " + "Current balance is $" + str(USER_BALANCE))
continue
else:
print ("Cannot be done. You have insufficient funds.")
elif answer== "check balance" or answer== "Check Balance":
print ("$" + str(USER_BALANCE))
elif answer== "exit" or answer== "Exit":
print ("Goodbye!")
accountfile.close()
break
else:
print ("I'm sorry, that is not an option")
Please help. I know this is a complete mess but any help would be greatly appreciated.

I have added comments to explain what your mistakes are, I did what was asked.
class BankAcc(object):
def __init__(self, name, pin, balance=10000.0): #If you want to give default balance if not provided explicitly do this
self.name = name #variable where value is stored = expression
self.pin = pin
self.balance = balance
def CheckUser(self, name, pin): #A function to check wheather the user is valid or not
try:
if name != self.name or pin != self.pin:
raise ValueError
print("Name and Pin Matches")
except ValueError:
print("Name or Password is not correct")
exit(0)
def __str__(self):
return "{}'s Bank Account with Balance {}".format(self.name, self.balance) #using only one substition in the string but providing 2 variables
def checkbalance(self):
return '$' + str(self.balance) #self is the instance of the class for printing balance use self.balance
def deposit(self, amount):
self.balance += amount #self.ammount will create a new property but i think you want to increase your balance
def withdraw(self, amount):
try: #use try catct if raising an excpetion
if self.balance >= amount: #balance should be greater than and equal to the ammount
self.balance -= amount
else:
raise ValueError
except ValueError: #Handle your exception
print("Cannot be done. You have insufficient funds.")
def filedata(self): #An extra function for writing in the file.
return "{},{},{}".format(self.name,self.pin,self.balance)
accountfile = open("ATMACC.txt", "r+") #"r+" should be used becuase you are reading and writing
accountfiledata=accountfile.read().split(",") #Can be done in the class it self
BankUser = BankAcc(accountfiledata[0],accountfiledata[1],float(accountfiledata[2])) #For simplicity i used comma seperated data and created an instance of it
name=input("What is your name? ")
pin=input("What is your Pin #? ")
BankUser.CheckUser(name, pin)
#accountfile.write("Name: " + name + "\n" + "PIN: " + pin + "\n") #You did not specify that you want to write in file as well
#USER_BALANCE = 10000 it is not needed
while True: #For multiple options use numbers instead of words such as 1 for deposit etc
answer=input("Would you like to deposit, withdraw, check balance, or exit? ")
if answer=="deposit" or answer== "Deposit":
x= input("How much would you like to deposit? ")
BankUser.deposit(float(x)) #use your deposit function
print ("Your new balance is: " + BankUser.checkbalance())
#continue #Why using continue, no need for it
elif answer== "withdraw" or answer== "Withdraw":
y= input("How much would you like to withdraw? ")
BankUser.withdraw(float(y)) #Use Your withdraw function why reapeating your self
elif answer== "check balance" or answer== "Check Balance":
print(BankUser.checkbalance())
elif answer== "exit" or answer== "Exit":
print ("Goodbye!")
accountfile.close()
exit(0)
else:
print ("I'm sorry, that is not an option")
accountfile.seek(0) #I dont know whether you want to record all tranction or a single one
accountfile.truncate() #perform write function at the last
accountfile.write(BankUser.filedata())
And text file format is ATMACC.txt
Himanshu,1111,65612.0

Related

Started to teach myself Python and str if statements seem to not be working correctly

Trying to create a simple transaction simulation just for practice using if statements, but when input is requested it defaults to the same if and doesn't change even when string literal variables are set in place.
I've tired moving things around, but everytime I run the code and it prompts me with Type "Deposit or "Withdraw" it will skip over proceed1 variable, and default to the amount1 variable input by prompting the user to "how much would you like to deposit."
import time
checking = 0
savings = 0
proceed1 = "Checking" or "checking"
proceed2 = "Savings" or "savings"
deposit = "Deposit" or "deposit"
withdraw = "Withdraw" or "withdraw"
time.sleep(1)
print("Thank you for choosing the Bank of Kegan")
time.sleep(1)
choice = str(input("Type \"Deposit\" or \"Withdraw\" \n "))
if choice == deposit:
print("Deposit Transaction Initiated: Checking ")
time.sleep(.5)
print("Please choose an account you would like to Deposit into. ")
account_choice = str(input("Type \"Checking\" or \"Savings\" \n "))
if account_choice == proceed1:
print("Checking Account Loading... \n")
time.sleep(2)
print("Checking: $", checking, "\n")
time.sleep(2)
amount1 = int(input("Please type how much you'd like to deposit. \n "))
time.sleep(.5)
print("$", amount1, "Transaction Pending...")
time.sleep(2)
checking = (checking + amount1)
print("Your new balance is: ")
print("$", checking)
exit()
elif account_choice == proceed2:
print("Savings Account Loading... ")
time.sleep(2)
print("Savings: $", savings)
time.sleep(2)
amount2 = int(input("Please type how much you'd like to deposit. \n "))
time.sleep(.5)
print("$", amount2, "Transaction Pending... ")
time.sleep(2)
savings = (savings + amount2)
print("Your new balance is: ")
print("$", savings)
exit()
else:
print("Please choose a valid argument ")
elif choice == withdraw:
print("Withdraw Transaction Initiated: Checking ")
print("Type what account you would like to withdraw from. ")
choice2 = str(input("Checking or Savings"))
if choice2 == proceed1:
print("Withdraw Transaction Initiated: Checking ")
print("Checking Account Loading... ")
time.sleep(2)
print("Checking \n Balance: ", checking)
withdraw1 = int(input("Type how much you would like to withdraw. "))
print("$", withdraw1, "withdraw transaction pending... ")
time.sleep(2)
if checking == 0:
print("You broke broke, make some money and come back later.")
else:
checking = withdraw1 - checking
print("your new balance is: $", checking)
elif choice2 == proceed2:
time.sleep(.5)
print("Savings Account Loading... ")
time.sleep(2)
print("Savings \n Balance: ", savings)
withdraw2 = int(input("Type how much you would like to withdraw. "))
print("$", withdraw2, "withdraw transaction pending... ")
time.sleep(2)
if savings == 0:
print("You broke broke, make some money and come back later.")
else:
savings = withdraw2 - savings
print("your new balance is: $", savings)
else:
print("Please choose a valid argument.")

How to return the right positive number in python whithou changing the initial variable?

I have create functions to simulate ATM system, when asking the user to make deposit everything goes well but the problem is when the user make a withdraw. If the amount is greater than the balance I have the new balance in negative value. And need some help to correct this behavior.
My functions:
def show_balance(balance):
print(f"Current Balance: ${balance}")
def deposit(balance):
amount = input("Enter amount to deposit: ")
amount = float(amount)
result = balance + amount
return result
def withdraw(balance):
withdraw = input("Enter amount to withdraw: ")
withdraw = float(withdraw)
result = balance - withdraw
return result
Here is when using the functions:
# Display ATM menu to user
while True:
option = input("Choose an option: ")
if option == "1":
account.show_balance(balance)
elif option == "2":
balance = account.deposit(balance)
account.show_balance(balance)
elif option == "3":
balance = account.withdraw(balance)
account.show_balance(balance)
while True:
if balance < 0:
print("You do not have this money?")
break
else:
print("Please, provide a valid option")
Now when adding 50 using option "2" everithing works well. When the withdraw is < the balance (55) it just return a nagative value (-5). I want to print the massage: "You do not have this money?", but also keep the balance to the right amount (50 -55) => balance remain 50 and ask the user to try again.
#AKX -> Based on your precious advice, I have fixed the function doing the following:
def withdraw(balance):
withdraw = input("Enter amount to withdraw: ")
withdraw = float(withdraw)
if withdraw <= balance:
result = balance - withdraw
return result
elif withdraw > balance:
print("You do not have this money?")
return balance

How would I instantiate several accounts from a bank account class?

I have to write code to instantiate several objects (bank accounts) from a class. I wrote the functions for checking the balance, withdrawing, and depositing with a single object. However, I can't figure how to make it so that the class is repeated for each object. I also can't figure out how to make it so that the choice to check the balance, deposit, or withdraw from the object applies to the correct object. In addition to this, I don't know how to get the functions to check the balance, deposit, and withdraw to run for each object.
Code:
class Account:
def __init__(self, name, account_number, balance):
print("Welcome to the bank.")
self.name=name
self.account_number=account_number
self.balance=balance
def check_balance(self):
print ("Balance:", self.balance)
def deposit(self):
print("Current balance:", self.balance)
str2=input("How much would you like to deposit? ")
str2=int(str2)
print ("Current Balance:", self.balance + str2)
def withdraw(self):
print ("Current Balance", self.balance)
str4=input("How much would you like to withdraw? ")
str4=int(str4)
if self.balance - str4 < 0:
print("Unable to process. Doing this will result in a negative balance.")
elif self.balance - str4 >= 0:
print("Current Balance:", self.balance - str4)
str3=input("Would you like to check the balance of the account, deposit money into the account, or withdraw money from the account? ")
if str3=="check the balance":
self.check_balance()
elif str3=="deposit money":
self.deposit()
elif str3=="withdraw money":
self.withdraw()
else:
print("Unable to process.")
Fred=Account("Fred",20,30)
John=Account("John",30,40)
Michelle=Account("Michelle",40,50)
Ann=Account("Ann",50,60)
You have some design problems here.
Don't store the accounts in 4 separate variables. Store them in a list so you can look them up by account number (or by name, if you want to add that). That will make it easier to save the accounts to file and read them back, which you will need to do.
The Account is just a place to store information. Don't have it do any I/O. Don't have it interact with the user.
You need to ask the user which account to work with.
You should loop until they're done.
Here, I'm asking for an account number every time. To make this smarter, you would ask for an account one, and keep allowing options on that account, with another menu item to switch to a different account.
You COULD store the accounts in a dictionary with the account number as the key. That would be more sensible than a simple list.
class Account:
def __init__(self, name, account_number, balance):
self.name=name
self.account_number=account_number
self.balance=balance
def deposit(self, amt):
self.balance += amt
return self.balance
def withdraw(self,amt):
if self.balance < amt:
return self.balance - amt
self.balance -= amt
return self.balance
accounts = [
Account("Fred",20,30),
Account("John",30,40),
Account("Michelle",40,50),
Account("Ann",50,60)
]
print("Welcome to the bank.")
while True:
acct = int(input("Which account number are you working with today? "))
acct = [a for a in accounts if a.account_number == acct]
if not acct:
print("That account doesn't exist.")
continue
acct = acct[0]
print("\nBalance: ", acct.balance)
print("Would you like to:")
print(" 1. Check the balance")
print(" 2. Deposit money")
print(" 3. Withdraw money")
print(" 4. Quit")
str3 = input("Pick in option: ")
if str3=="1":
print("Balance: ", acct.balance)
elif str3=="2":
amt=int(input("How much would you like to deposit? "))
acct.deposit( amt )
elif str3=="3":
amt=int(input("How much would you like to withdraw? "))
if acct.withdraw( amt ) < 0:
print("Unable to process. Doing this will result in a negative balance.")
elif str3=="4":
break
else:
print("Unrecognized.")

ATM program not looping properly in Python

I'm making a ATM-type program in which I have to ask the user if they want to deposit, withdraw, or check their balance in their savings or checking account, but only if the pin they enter is 1234. I've been instructed to use global variables and initialize savings and checking as 0. All of my functions are working properly, but when the program loops again the savings and checking balances are still 0, even when the user has just deposited money into either account. I'm not sure which part of my code is messing this up, but any help is greatly appreciated.
#Create global variables
Checking = 0
Saving = 0
def main():
pin_number = input("Please enter your pin number ")
stop = False
while not is_authorized(pin_number) and stop!= True:
if pin_number == "0":
stop = True
if pin_number == "1234":
stop = False
if stop != True:
while True:
choice = display_menu()
if choice == 1:
deposit()
elif choice == 2:
withdraw()
elif choice == 3:
check_balance()
def is_authorized (pin_number):
if pin_number == "1234":
return True
else:
return False
def display_menu():
print('1) Deposit')
print('2) Withdraw')
print('3) Check amount')
choice = int(input("Please enter the number of your choice: "))
return choice
def deposit():
depositing=str(input("Would you like to deposit into your savings
or checking? "))
if depositing == "savings":
depo = float(input("How much would you like to deposit? "))
new_savings = Saving + depo
print ("Your new balance is" +str (new_savings))
elif depositing == "checkings":
depo = input(int("How much would you like to deposit? "))
new_checking = Checking + depo
print ("Your new balance is" +str (new_checking))
def withdraw():
print ("Your savings account balance is " +str (Saving))
print ("Your checkings account balance is " +str (Checking))
withdrawing=str(input("Would you like to withdraw from your checking or savings? "))
if withdrawing == "checking":
withdraw = int(input("How much would you like to withdraw? "))
checking2= Checking - withdraw
print ("Your new balance is" +str (checking2))
elif withdrawing == "savings":
withdraw = int(input("How much would you like to withdraw? "))
savings2= Saving - withdraw
print ("Your new balance is" +str (savings2))
def check_balance():
checkbalance= input("Would you like to check your savings or checking? ")
if checkbalance == "savings":
print (Saving)
elif checkbalance == "checking":
print ("Your balance is $" +str (Checking))
main()
In order to modify values Saving and Checking in your functions you have to declare them global inside the function, not the use of global is not the most optimal, as far as I know, but it seems that is your task at hand. Your while loop can be simplified, by using while True and break. Along the way I found a few small things I touched up, I would also consider changing Saving to Savings since that is the keyword you are accepting as a response, makes things easier for you.
Checking = 0
Saving = 0
def main():
while True:
pin_number = input("Please enter your pin number ")
while pin_number not in ('0','1234'):
pin_number = input("Please enter your pin number ")
if pin_number == "0":
break
elif pin_number == "1234":
choice = display_menu()
if choice == 1:
deposit()
elif choice == 2:
withdraw()
elif choice == 3:
check_balance()
def is_authorized (pin_number):
if pin_number == "1234":
return True
else:
return False
def display_menu():
print('1) Deposit')
print('2) Withdraw')
print('3) Check amount')
choice = int(input("Please enter the number of your choice: "))
return choice
def deposit():
global Checking, Saving
depositing=str(input("Would you like to deposit into your savings or checking? "))
if depositing == "savings":
depo = float(input("How much would you like to deposit? "))
Saving += depo # use += here
print ("Your new balance is " +str (Saving))
elif depositing == "checking": # changed to checking
depo = int(input("How much would you like to deposit? "))
Checking += depo
print ("Your new balance is " +str (Checking))
def withdraw():
global Checking, Saving
print ("Your savings account balance is " +str (Saving))
print ("Your checkings account balance is " +str (Checking))
withdrawing=str(input("Would you like to withdraw from your checking or savings? "))
if withdrawing == "checking":
withdraw = int(input("How much would you like to withdraw? "))
Checking -= withdraw
print ("Your new balance is " +str (Checking))
elif withdrawing == "savings":
withdraw = int(input("How much would you like to withdraw? "))
Saving -= withdraw
print ("Your new balance is " +str (Saving))
def check_balance():
global Checking, Saving
checkbalance= input("Would you like to check your savings or checking? ")
if checkbalance == "savings":
print (Saving)
elif checkbalance == "checking":
print ("Your balance is $" +str (Checking))
main()

Transaction Record of an ATM Program in Python

My assignment is to keep a record of the transactions of an ATM program in a text file. After every deposit or withdraw you must update the file with the transaction type, amount deposited/withdrawn, and updated balance. I am able to get the text file to print out the current balance but only for one deposit/withdraw. Additionally, when the program runs it is supposed to open the file with the transactions and find the current balance for the account, but each time I run the program the new text just replaces the old.
Here is my code:
balancefile=open("balancefile.txt", "w")
balancefile.write("Starting balance is $10000 \n")
USER_BALANCE=10000
name=input("What is your name? ")
print(name +"," + " " + "Your current balance is: $" + str(USER_BALANCE))
while True:
answer=input("Would you like to deposit, withdraw, check balance, or exit? ")
if answer=="deposit" or answer== "Deposit":
x= input("How much would you like to deposit? ")
USER_BALANCE += float(x)
print (name + "," + " " + "Your new balance is: $" + str(USER_BALANCE))
balancefile.write("You have deposited an amount of $" + x + "." + " " + "Current balance is $" + str(USER_BALANCE) +"\n")
continue
elif answer== "withdraw" or answer== "Withdraw":
y= input("How much would you like to withdraw? ")
if float (y)<=USER_BALANCE:
USER_BALANCE -= float(y)
print (name + "," + " " + "Your new balance is: $" + str(USER_BALANCE))
balancefile.write("You withdrew an amount of $" + y + "." + " " + "Current balance is $" + str(USER_BALANCE) + "\n")
continue
else:
print ("Cannot be done. You have insufficient funds.")
elif answer== "check balance" or answer== "Check Balance":
print ("$" + str(USER_BALANCE))
elif answer== "exit" or answer== "Exit":
print ("Goodbye!")
balancefile.close()
break
else:
print ("I'm sorry, that is not an option")
Please help! To clarify, the original amount in the account is $10,000 but you are supposed to be able to re-enter the program after exiting using the last updated balance in the text file.
As the commenters have noted, the file mode 'w' will truncate the file proir to write, and 'a' will open a file for appending. This is described in further detail in the Python documentation.

Categories

Resources