Transaction Record of an ATM Program in Python - 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.

Related

I'm getting the wrong output in my if statment

I'm new to python and am trying to fix this and By defualt its running the else statment I don't understand and need help. I'm new so please dumb your answers down to my -5 iq
menu = "Baguette , Crossiant , Coffee , Tea , Cappuccino "
print(menu)
if "" > menu:
order = input("What Would you like? \n ")
amount = input("How many " + order + " would you like?")
print( name + " Your " + amount + " " + order + " will be ready soon!\n\n\n")
price = int(4)
#converts number into intenger to do math correctly (int)
total = price * int(amount)
#turns total into string intead of intenger to prevent error in terminal
print("Thank you, your total is: $" + str(total))
print("Your " + amount + " of " + order + " is ready!")
print("Please enjoy you " + order + "!")
print("Please come again!")
else:
#If not on menu stops running
print("Sorry Thats not on the menu")
quit()
I changed the if "" to on_menu and list the options but it didn't work, and I asked people on discord.
menu = ["Baguette" , "Crossiant" , "Coffee" , "Tea" , "Cappuccino "]
count = 0
for item in menu:
print(str(count) +" -> "+str(item))
count += 1
order = int(input("\n What Would you like? \n "))
if order > len(menu) or order < 0 or order == "" or not menu[order]:
print("Sorry Thats not on the menu")
quit()
orderCount = int(input("How many " + menu[order] + " would you like?"))
print("Your " + str(orderCount) + " " + menu[order] + " will be ready soon!\n\n\n")
amount = int(4) * int(orderCount)
print("Thank you, your total is: $" + str(amount))
print("Your " + str(amount) + " of " + str(menu[order]) + " is ready!")
print("Please enjoy you " + str(menu[order]) + "!")
print("Please come again!")
Currently you are not checking the user input, you are just checking for a False statement based on what you defined. You need to check if the user input is on the menu, else quit the program.
menu = "Baguette , Crossiant , Coffee , Tea , Cappuccino "
print(menu)
name = input("What your name? \n ")
order = input("What Would you like? \n ")
if not order.lower() in menu.lower(): # checking if user input is in the menu
#If not on menu stops running
print("Sorry Thats not on the menu")
quit()
amount = input("How many " + order + " would you like?")
print( name + " Your " + amount + " " + order + " will be ready soon!\n\n\n")
price = int(4)
#converts number into intenger to do math correctly (int)
total = price * int(amount)
#turns total into string intead of intenger to prevent error in terminal
print("Thank you, your total is: $" + str(total))
print("Your " + amount + " of " + order + " is ready!")
print("Please enjoy you " + order + "!")
print("Please come again!")
#input name
name = input("What is your name?\n")
#create menu
menu = "Baguette, Crossiant, Coffee, Tea and Cappuccino"
#display menu
print(menu)
#input order
order = input("What would you like?\n")
#if the order item is in the menu
if order in menu:
#input quantity
amount = input("How many " + order + "s would you like? ")
#display message
print( name + " Your " + amount + " " + order + " will be ready soon!\n\n\n")
#setting price of all items to 4
price = 4
#calculating total
total = price * int(amount)
#turns total into string intead of intenger to prevent error in terminal
print("Thank you, your total is: $" + str(total))
print("Your " + amount + " of " + order + " is ready!")
print("Please enjoy you " + order + "!")
print("Please come again!")
#if the item is not in menu
else:
#display message
print("Sorry Thats not on the menu")
Hope this helps! I have added the explanation as comments.

Python Not Using Elif Statement

I'm trying to make a virtual coffee shop, in which the amount of an item a customer asks for would adjust the total for payment. However, when I run my code, and I enter more than 1 of an item, it simply skips the step that would inform the user of their total.
Code:
import time
print("Hello! Welcome to George's Coffee.")
name = input("What is your name for the order?\n")
print("\nHello " + name + "! Thank you for coming to George's Coffee!\n")
print("On todays menu, we have the following:\n" + "Lattee\n" + "Hot Chocolate\n" + "Mocha\n" + "Celcius\n" + "Cappuchino\n" + "Black Coffee\n" + "All items are $8 because we need money to fund the hacking of the government.")
price = 8
order = input("\nWhat would you like to order today?\n")
quantity = input("How many " + order + "s would you like?\n")
#singular (=1)
if quantity == "1":
if order == "Lattee":
latte_total = float(2.95) * int(quantity)
print("Amazing choice! That will be $" + str(latte_total) + ". Please enter your credit card.")
elif order == "Hot Chocolate":
hot_chocolate_total = 2 * int(quantity)
print("Amazing choice! That will be $" + str(hot_chocolate_total) + ". Please enter your credit card.")
elif order == "Mocha":
mocha_total = 5 * int(quantity)
print("Amazing choice! That will be $" + str(mocha_total) + ". Please enter your credit card.")
elif order == "Celcius":
cel_total = 2 * int(quantity)
print("Amazing choice! That will be $" + str(cel_total) + ". Please enter your credit card.")
elif order == "Cappuchino":
capp_total = 6 * int(quantity)
print("Amazing choice! That will be $" + str(capp_total) + ". Please enter your credit card.")
elif order == "Black Coffee":
coffee_total = 3 * int(quantity)
print("Amazing choice! That will be $" + str(coffee_total) + ". Please enter your credit card.")
else:
total = price * int(quantity)
print("Amazing choice! That will be $" + str(total) + ". Please enter your credit card.")
time.sleep(3)
print("\nYour " + quantity + " " + order + " will be ready soon! Please have a seat, and we will call your name when it's ready.\n")
time.sleep(10)
print(name + "! Your " + order + " is ready! Please come collect it.\n")
time.sleep(2)
print("Enjoy your beverage, " + name + ("!"))
Output: terminal output
This is my first time posting, so it made it a link
Output when I only do 1: terminal output with only 1
Let me know how I can solve this. Thanks for your help in advance.
In your code you are using
if quantity == "1":
do all the price calculations
That's why it is only working when you get just 1 item, quantity is equal to "1". When you use another quantity the if statement just ignores the rest of the code.
To solve this issue you can delete that line.
import time
print("Hello! Welcome to George's Coffee.")
name = input("What is your name for the order?\n")
print("\nHello " + name + "! Thank you for coming to George's Coffee!\n")
print("On todays menu, we have the following:\n" + "Lattee\n" + "Hot Chocolate\n" + "Mocha\n" + "Celcius\n" + "Cappuchino\n" + "Black Coffee\n" + "All items are $8 because we need money to fund the hacking of the government.")
price = 8
order = input("\nWhat would you like to order today?\n")
quantity = input("How many " + order + "s would you like?\n")
#singular (=1)
if order == "Lattee":
latte_total = float(2.95) * int(quantity)
print("Amazing choice! That will be $" + str(latte_total) + ". Please enter your credit card.")
elif order == "Hot Chocolate":
hot_chocolate_total = 2 * int(quantity)
print("Amazing choice! That will be $" + str(hot_chocolate_total) + ". Please enter your credit card.")
elif order == "Mocha":
mocha_total = 5 * int(quantity)
print("Amazing choice! That will be $" + str(mocha_total) + ". Please enter your credit card.")
elif order == "Celcius":
cel_total = 2 * int(quantity)
print("Amazing choice! That will be $" + str(cel_total) + ". Please enter your credit card.")
elif order == "Cappuchino":
capp_total = 6 * int(quantity)
print("Amazing choice! That will be $" + str(capp_total) + ". Please enter your credit card.")
elif order == "Black Coffee":
coffee_total = 3 * int(quantity)
print("Amazing choice! That will be $" + str(coffee_total) + ". Please enter your credit card.")
else:
total = price * int(quantity)
print("Amazing choice! That will be $" + str(total) + ". Please enter your credit card.")
time.sleep(3)
print("\nYour " + quantity + " " + order + " will be ready soon! Please have a seat, and we will call your name when it's ready.\n")
time.sleep(10)
print(name + "! Your " + order + " is ready! Please come collect it.\n")
time.sleep(2)
print("Enjoy your beverage, " + name + ("!"))

How to ignore certain strings from user input?

Beginner question:
How do I have my input code ignore certain strings of text?
What is your name human? I'm Fred
How old are you I'm Fred?
How do I ignore user input of the word "I'm"?
How old are you I'm Fred? I'm 25
Ahh, Fred, I'm 25 isn't that old.
How do I again ignore user input when dealing with integers instead?
This is the code I have so far:
name = input("What is your name human? ")
while True:
try:
age = int(float(input("How old are you " + name + "? ")))
if age >= 50:
print(str(age) + "! Wow " + name + ", you're older than most of the oldest computers!")
else:
print ("Ahh, " + name + ", " + str(age) + " isn't that old.")
break
except ValueError:
print("No, I asked how old you were... ")
print("Let us try again.")
You could use .replace('replace what','replace with') in order to acheive that.
In this scenario, you can use something like:
name = input("What is your name human? ").replace("I'm ","").title()
while True:
try:
age = int(input("How old are you " + name + "? ").replace("I'm ",""))
if age >= 50:
print(str(age) + "! Wow " + name + ", you're older than most of the oldest computers!")
else:
print ("Ahh, " + name + ", " + str(age) + " isn't that old.")
break
except ValueError:
print("No, I asked how old you were... ")
print("Let us try again.")
Similarly, you can use for the words you think the user might probably enter, this is one way of doing it.
Why not use the list of words that should be ignored or removed from the input, i suggest you the following solution.
toIgnore = ["I'm ", "my name is ", "i am ", "you can call me "]
name = input("What is your name human? ")
for word in toIgnore:
name = name.replace(word, "")
while True:
try:
age = int(float(input("How old are you " + name + "? ")))
if age >= 50:
print(str(age) + "! Wow " + name + ", you're older than most of the oldest computers!")
else:
print ("Ahh, " + name + ", " + str(age) + " isn't that old.")
break
except ValueError:
print("No, I asked how old you were... ")
print("Let us try again.")
The output is following

The game over line isn't working. Why isn't it correctly displaying the games won and lost?

This is my code for a game of 21 or Blackjack. On the final line it won't display the number of games won and number of games lost but I can't figure out how to fix it. Can someone help me correct this? I did this on python 3.6.1
P.S. If there is anything else that can be improved here, feedback would be much appreciated.
import random
from random import choice
import time
import colorama
from colorama import Fore, Back, Style
name = str(input("Welcome to " + Fore.YELLOW + "21" + Style.RESET_ALL + "! I'll be your dealer. \nWhat's your name?"))
instructions=""
while instructions!="N" and instructions!="Y":
instructions=str(input("Would you like to see the Instructions? Y/N"))
if instructions!="N" and instructions!="Y":
print("That is not a valid answer.")
else:
time.sleep(1)
if instructions=="Y":
print(Fore.GREEN + "Instructions:" + Style.RESET_ALL + "\nYour objective is to get as close as you can to " + Fore.YELLOW + "21" + Style.RESET_ALL + ".\n>Each round, you will be dealt two standard cards. You must add these and the person with the closest total wins. \n>You will choose whether to 'hit' or 'miss' every round. If you hit, you get dealt another card. However, be careful as going over " + Fore.YELLOW + "21 " + Style.RESET_ALL + "causes you to bust and lose! \n>Picture cards are worth 10 points each.\n>Aces are 1 or 11, randomly.")
time.sleep(1)
else:
print("")
rounds=int(input("How many rounds do you want to play " + name + "?"))
gamesLost=0
gamesWon=0
def twentyone():
roun=0
for i in range(0,rounds):
gamesLost=0
gamesWon=0
roun+=1
print("Round " + str(roun))
cards=['Ace','Ace','Ace','Ace','2','2','2','2','3','3','3','3','4','4','4','4','5','5','5','5','6','6','6','6','7','7','7','7','8','8','8','8','9','9','9','9','10','10','10','10','Jack','Jack','Jack','Jack','Queen','Queen','Queen','Queen','King','King','King','King']
cardVal = {'Ace':random.randint(1,11),'King':10,'Queen':10,'Jack':10,'10':10,'9':9,'8':8,'7':7,'6':6,'5':5,'4':4,'3':3,'2':2}
card1=random.choice(cards)
cards.remove(card1)
card2=random.choice(cards)
cards.remove(card2)
hands=(str(card1) + ", " + str(card2))
playerHand = cardVal[card1]+cardVal[card2]
print("Your hand is " + hands + ". Your hand is worth " + str(playerHand) + ".")
hit=""
while hit!="H" and hit!="S" and hit!="h" and hit!="s":
hit=str(input("Do you want to hit (H) or stay (S)?"))
if hit!="H" and hit!="S" and hit!="h" and hit!="s":
print("That is not a valid answer.")
else:
time.sleep(0.01)
while hit=="H" or hit=="h":
card=random.choice(cards)
cards.remove(card)
playerHand+=cardVal[card]
hands=(hands + ", " + str(card))
print("Your hand is " + hands + ". Your hand is worth " + str(playerHand) + ".")
if playerHand>21:
break
else:
time.sleep(0.01)
hit=str(input("Do you want to hit (H) or stay (S)?"))
if playerHand>21:
print("Sorry, you bust!")
gamesLost+=1
i+=1
else:
time.sleep(0.01)
cpuCard1=random.choice(cards)
cards.remove(cpuCard1)
cpuCard2=random.choice(cards)
cards.remove(cpuCard2)
handsCPU=(str(cpuCard1) + ", " + str(cpuCard2))
computerHand=cardVal[cpuCard1]+cardVal[cpuCard2]
while computerHand<17:
if computerHand<17:
cpuCard=random.choice(cards)
cards.remove(cpuCard)
computerHand+=cardVal[cpuCard]
handsCPU=(handsCPU + ", " + str(cpuCard))
else:
time.sleep(0.01)
if computerHand>21:
print("I'm bust! You win.")
gamesWon+=1
i+=1
elif computerHand>playerHand:
print("My hand is " + str(handsCPU) + ". It is worth " + str(computerHand) + ". You lose.")
gamesLost+=1
i+=1
else:
print("My hand is " + str(handsCPU) + ". It is worth " + str(computerHand) + ". You win.")
gamesLost+=1
i+=1
twentyone()
print("\nGame Over!")
print("You won " + str(gamesWon) + " and lost " + str(gamesLost) + ".")
again=str(input("Do you want to go again? Y/N"))
if again=="Y":
rounds=int(input("How many rounds do you want to play " + name + "?"))
twentyone()
elif again=="N":
print("Have a nice day.")
else:
print("Have a nice day.")
Unfortunately I can't test it myself since I don't have all modules. But I assume your issue is that the line print says you won and lost 0 games every time.
It looks like you're resetting your game-counters with every new game:
for i in range(0,rounds):
gamesLost=0
gamesWon=0
You play one game, record games won and lost and then reset both to 0 for the next game when the loop starts over. Since you're also initialising both counters just before the loop - but also outside the def - it should work if you remove both lines. Or you can move the lines before the loop and maybe remove the other copy if it is redundant. Defining the counters inside your function is the better approach, though.

ATM Account Homework (Classes, Textfiles, Objects)

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

Categories

Resources