Writing to a file help in python 2.7 - python

This is my atm, it has a pin code protection thing and can basically run like a normal atm, however i need to make it so it remembers you and your balance everytime you log out and in etc. ive tried doing this with a blank text file(nothing is in the text file) and linked it into my code (as you can see) but it doesnt work, im not sure what i have to add etc. any help?
balance = float(0)
userInput = None
path = 'N:\ATM.txt'
username = 'some_username'
with open(path, 'r') as file:
for user in file.readlines():
if user == username:
print("welcome back")
print("Hello, Welcome to the ATM")
print("")
print("Please begin with creating an account")
name = raw_input("Enter your name: ")
saved_code = str(raw_input("Please enter a 4 digit pin to use as your passcode: "))
try:
int(saved_code)
if len(saved_code)!=4:
raise
except Exception, e:
print("Error: Pin is not a valid 4 digit code")
exit()
totalTrails = 3;
currentTrail = 0;
status = 1;
while currentTrail < totalTrails:
user_code =str(raw_input('Please enter the 4 digit pin on your card:'))
if user_code==saved_code:
status=0
break;
else:
currentTrail+=1
if status==0:
print("correct pin!")
else:
print("You tried to enter a wrong code more than three times.")
exit();
print "Hello , welcome to the ATM"
while userInput != "4":
userInput = raw_input("\n what would you like to do?\n\n (1)Check balance\n (2)Insert funds\n" +
" (3)Withdraw funds\n (4)Exit the ATM\n" )
if userInput == "1":
print "your balance is", "£" , balance
elif userInput == "2":
funds = float(raw_input("Enter how much money you want to add"))
balance = balance + funds
elif userInput == "3":
withdraw = float(raw_input("Enter how much money you want to withdraw..."))
balance = balance - withdraw
elif userInput == "4":
print "Thanks for using the ATM!"

You are opening the file in 'r' mode, which means read only, you should use 'r+' if you want to read and write in it.
You are not writing anything to the file - that's done by write() method - in your case
file.write("string I want to write to the file");
After you are done writing to the file, close it - file.close()

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 remove the parenthesis and a comma in the output

I am writing a program in python for a banking application using arrays and functions. Here's my code:
NamesArray=[]
AccountNumbersArray=[]
BalanceArray=[]
def PopulateAccounts():
for position in range(5):
name = input("Please enter a name: ")
account = input("Please enter an account number: ")
balance = input("Please enter a balance: ")
NamesArray.append(name)
AccountNumbersArray.append(account)
BalanceArray.append(balance)
def SearchAccounts():
accounttosearch = input("Please enter the account number to search: ")
for position in range(5):
if (accounttosearch==AccountNumbersArray[position]):
print("Name is: " +NamesArray[position])
print(NamesArray[position],"account has the balance of: ",(BalanceArray[position]))
break
if position>4:
print("The account number not found!")
while True:
print("**** MENU OPTIONS ****")
print("Type P to populate accounts")
print("Type S to search for account")
print("Type E to exit")
choice = input("Please enter your choice: ")
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
break
else:
print("Invalid choice. Please try again!")
Everything is fine now, but when I run the program and search for an account. For example, when I search an account the output shows ('name', 'account has the balance of: ', 312) instead of name account has the balance of: 312 How do I fix this?
In the line
print(NamesArray[position],"account has the balance of: ",(BalanceArray[position]))
you should use string concatenation to add the different strings. One way to do this would be like this:
print(NamesArray[position] + " account has the balance of: " + str(BalanceArray[position]))
u are using old python version,
replace your line with this :
print(NamesArray[position] + "account has the balance of: " + (BalanceArray[position]))
use ' + ' instead of comma

What method to use in "ATM" based program

I've started with a assignment for a ATM code, I'm supposed to use text file in some way or another. so far I've got this:
print("Hello, and welcome to the ATM machine!\n")
a_pin = {1111, 2222, 3333, 4444}
def process():
pin = int(input("\nplease enter below your 4-digit pin number: "))
if pin in a_pin:
if pin == (1111):
f = open("a.txt", "r")
elif pin == (2222):
f = open("b.txt", "r")
elif pin == (3333):
f = open("c.txt", "r")
elif pin == (4444):
f = open("d.txt", "r")
print(
"""
MENU:
1: view your current balance
2: make a withdraw
3: make a deposit
4: exit
""")
option = input("\nwhat would you like to do? ")
if option == "1":
print(f.read())
elif option == "2":
y = str(input("\nHow much would you like you like to withdraw? "))
f.write(y)
print("Excellent, your transaction is complete!")
elif option == "3":
z = str(input("\nHow much would you like to deposit? "))
f.write(z)
print("Excellent, your transaction is complete!")
elif option == "4":
input("Please press the enter key to exit.")
else:
print("\nthat was a wrong pin number!")
x = input("\nwould you like to try again? '(y/n)' ")
if x == "y":
process()
else:
input("\npress the enter key to exit.")
process()
The code works as of now, but I want to save some time by asking how to most effectively overwrite content on the text files when withdrawing/depositing.
I was thinking of pickled files... but will be very happy for any suggestions, since normal commands like write dont really work for this task, if i want to display the new ammount to user after a withdraw/deposit.
Many thanks!
The key point is to consider the necessary "mode" to open the file so that it can be not only be read (r) but also modified (r+):
if pin == (1111):
f = open("a.txt", "r+")
elif pin == (2222):
f = open("b.txt", "r+")
elif pin == (3333):
f = open("c.txt", "r+")
elif pin == (4444):
f = open("d.txt", "r+")
Then store the current balance in the file, and update it after each transaction.
# read current balance from file and save its value
bal = float(f.read().strip('\n')) # or replace float() with int()
# reset file pointer to beginning of file before updating contents
f.seek(0)
if option == '1':
print(f.read()) # or simply, print(bal)
elif option == '2':
y = str(input("\nHow much would you like you like to withdraw? "))
bal -= int(y) # calculate new balance
f.write(str(bal)+'\n') # write new balance to file as a string
print("Excellent, your transaction is complete!")
elif option == '3':
z = str(input("\nHow much would you like to deposit? "))
bal += int(z)
f.write(str(bal)+'\n')
print("Excellent, your transaction is complete!")
If you are only keeping the most updated balance, try to open the text file in w+ mode, read the entire line and keep the value in your program, modify it however you want and finally write the end value and add an end of line. If should renew the value each time you run the program.

need help writing if else statement atm in python 2.7 for a pin protection

Im trying to create a pin protection thing for my ATM and you can enter a code etc. It then asks you for it however I want it so if you enter the wrong passcode it says incorrect try again and you cant continue into the main program. Maybe there could be a certain amount of tries? and also don't I have to write to a file if I want to save stuff? but nevermind that unless you know how I could use it in my code....
balance = float(0)
userInput = None
print("Hello, Welcome to the ATM")
print("")
print("Please begin with creating an account")
name = raw_input("Enter your name: ")
code = raw_input("Please enter a 4 digit pin to use as your passcode: ")
code = int(input('Please enter the 4 digit pin on your card:'))
if code == (code): print("correct pin!")
print "Hello , welcome to the ATM"
while userInput != "4":
userInput = raw_input("\n what would you like to do?\n\n (1)Check balance\n (2)Insert funds\n" +
" (3)Withdraw funds\n (4)Exit the ATM\n" )
if userInput == "1":
print "your balance is", "£" , balance
elif userInput == "2":
funds = float(raw_input("Enter how much money you want to add"))
balance = balance + funds
elif userInput == "3":
withdraw = float(raw_input("Enter how much money you want to withdraw..."))
balance = balance - withdraw
elif userInput == "4":
print "Thanks for using the ATM!"
balance = float(0)
userInput = None
print("Hello, Welcome to the ATM")
print("")
print("Please begin with creating an account")
name = raw_input("Enter your name: ")
# take the code as a string
saved_code = str(raw_input("Please enter a 4 digit pin to use as your passcode: "))
#validate that the code is a number and is 4 digit
try:
int(saved_code)
if len(saved_code)!=4:
raise
except Exception, e:
print("Error: Pin is not a valid 4 digit code")
exit()
# set trails and trail counter
totalTrails = 3;
currentTrail = 0;
status = 1;
# take input from user and compare codes
while currentTrail < totalTrails:
user_code =str(raw_input('Please enter the 4 digit pin on your card:'))
if user_code==saved_code:
status=0
break;
else:
currentTrail+=1
if status==0:
print("correct pin!")
else:
print("You tried to enter a wrong code more than three times.")
exit();
print "Hello , welcome to the ATM"
while userInput != "4":
userInput = raw_input("\n what would you like to do?\n\n (1)Check balance\n (2)Insert funds\n" +
" (3)Withdraw funds\n (4)Exit the ATM\n" )
if userInput == "1":
print "your balance is", "$" , balance
elif userInput == "2":
funds = float(raw_input("Enter how much money you want to add"))
balance = balance + funds
elif userInput == "3":
withdraw = float(raw_input("Enter how much money you want to withdraw..."))
balance = balance - withdraw
elif userInput == "4":
print "Thanks for using the ATM!"

local variable referenced before assignment python issue

So I'm coding a small project and I'm struggling with a certain aspect so far.
Here is the code:
import re
def clientDetails():
print("Welcome to the InHouse Solutions Room Painting Price Calculator")
print("STEP 1 - CLIENT DETAILS")
print("Please enter your full name")
userName = input(">>>")
print("Please enter your post code")
postCode = input(">>>")
print("Is your house a number, or a name?")
nameOrNumber = input(">>>")
if nameOrNumber == "number" or nameOrNumber == "Number":
print("Please enter your house number")
houseNumber = input(">>>")
elif nameOrNumber == "Name" or nameOrNumber == "name":
print("Please enter your house name")
houseName = input(">>>")
else:
print("Invalid")
house = (houseNumber) + (houseName)
address = (postCode) + ", " + (house)
print("Thank you for your information")
print (userName)
print (address)
print (" ")
print ("Is this information correct? Pleast enter Yes or No")
clientDetailsCorrect = input(">>>")
if clientDetailsCorrect == "no" or clientDetailsCorrect == "No":
clientDetails()
clientDetails()
Not sure what's going wrong as I haven't actually referenced the variable anywhere else. Someone help.
It would help if you posted the traceback.
That said, this line is the likely source of the problem:
house = (houseNumber) + (houseName)
The way your code is currently written, only one of houseNumber or houseName will be defined. So Python is likely complaining about the missing one.
Given how your code looks so far, it's probably better to just do:
print("Please enter your house name or number")
house = input(">>>")
And remove the house = (houseNumber) + (houseName) line.
Try this:
def clientDetails():
print("Welcome to the InHouse Solutions Room Painting Price Calculator\n")
print("STEP 1 - CLIENT DETAILS")
print("Please enter your full name")
userName = raw_input(">>>")
print("Please enter your post code")
postCode = raw_input(">>>")
print("Please enter your hose number or name")
house = raw_input(">>>")
address = "{}, {}".format(postCode, house)
print("Thank you for your information.\n")
print (userName)
print (address)
print (" ")
print ("Is this information correct? Pleast enter Yes or No")
clientDetailsCorrect = raw_input(">>>")
if clientDetailsCorrect.lower().startswith('n'):
clientDetails()
Using raw_input is better, it will input everything as a string. Also it will allow users to not type quotations to input text (I assume you will run this from CLI). If you later on need to separate houses that are numbers from names Python has very good string methods you can use to do so many wonderful things, I used a couple of them to simplify your code :)
N

Categories

Resources