What method to use in "ATM" based program - python

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.

Related

Writing a program to store high score in a .txt file

I'm writing a program for a school project in which I have to store high scores from user inputs. I have most of the program done, except for reading/writing from/to the file where I'm completely clueless.
The instructions said you should be able to have more than five users, but only the five best would be saved to the file. The scores should be sorted from highest to lowest, and a user is supposed to be able to update their previous score.
This is what I have so far:
class highscoreUser:
def __init__(self, name, score):
self.name = name
self.score = score
#classmethod
def from_input (cls):
return cls(
input("Type the name of the user:"),
float(input("Type the users score")),
)
print("Welcome to the program! Choose if you want to continue using this program or if you want to quit! \n -Press anything to continue. \n -or type quit to exit the program.")
choice = input("What would you like to do?:")
choice = choice.lower()
while choice != "quit":
try:
NUMBER = int(input ("How many people are adding their highscores?"))
except:
print("Something went wrong, try again!")
choice !="quit"
users = {}
try:
for i in range(NUMBER):
user = highscoreUser.from_input()
users[user.score] = user
except:
print("")
choice !="quit"
This is where I need help:
while choice != "quit":
print("\n.Now you have multiple choices: \n1.Uppdatera highscore. \n2.Hämta highscore \n3.Quit to exit the program ")
choice = input("What would you like to do?:")
choice = choice.lower()
# if choice == "1":
# with open("highscore.txt", "w") as scoreFile:
# ###Function to write/update the file with the user dictionary
# elif choice == "2":
# with open("highscore.txt", "r") as scoreFile
# ###Function for reading the highscore file
# elif choice == "quit":
# print("\nThank you for using this program!")
# else:
# print("\nSomething went wrong, try again!")
So your code should be something like this:
while choice != "quit":
print("\n.Now you have multiple choices: \n1.Uppdatera highscore. \n2.Hämta highscore \n3.Quit to exit the program ")
choice = input("What would you like to do?:")
choice = choice.lower()
if choice == "1":
with open('highscore.txt', 'wb') as f:
pickle.dump(users, f)
elif choice == "2":
with open('highscore.txt', 'rb') as f:
users = pickle.load(f)
elif choice == "quit":
print("\nThank you for using this program!")
else:
print("\nSomething went wrong, try again!")

How to keep python program running until it is closed by user and python file handling

So I want to create a program that takes input of some number of items and adds them to a text file. But I have encountered two problems. One, I don't know how to keep the program running until the user chooses to close it. Two, after the items are added to the text file and then displayed on the screen, it doesn't show the items in the correct order and some are even repeated and other left out. Below is my code, sorry if it's terrible I'm new to this. I had entered the letters s, i, c, and k, with each letter as an item and stored it to the text file and it returned this:
s
s
i
s
i
c
Here's my code
items = []
i= 0
ans = ""
print("Options:\n1: View existing items\n2: Add to list of items\n3: Clear saved items\n4: Make new list\n5. Exit program")
ans = input("\nWhat would you like to do?: ").strip()
if ans == "1":
f = open("items.txt", "r")
print(f.read())
f.close
elif ans == "2":
i = int(input("How many items would you like to enter: ").lower())
for i in range(i):
item = input("Enter the name of item: ").lower()
items.append(item)
f = open("items.txt", "a")
for item in items:
f.write(""+str(item)+"\n")
f.close
elif ans == "3":
f = open("items.txt", "r+")
f.truncate(0)
f.close
elif ans == "4":
i = int(input("How many items would you like to enter: ").lower())
for i in range(i):
item = input("Enter the name of item and price: ").lower()
items.append(item)
f = open("items2.txt", "w")
for item in items:
f.write(""+str(item)+"\n")
f.close
elif ans == "5":
quit()
else:
print("Choose by entering either 1, 2, 3 or 4.")
You'd do something like this:
# to write to a file
number_of_inputs = int(input("How many lines would you like to enter? "))
with open("inputs.txt", "w") as file:
for i in range(number_of_inputs):
file.write(
input("What would you like to write on line %s? " % (i))
+ "\n"
)
# to read from the file
with open("inputs.txt", "r") as file:
for line in file.readlines():
print(line)
I've come to this :
items = []
i = 0
leave = False
while leave is False:
print("Options:\n"
"1: View existing items\n"
"2: Add to list of items\n"
"3: Clear saved items\n"
"4: Make new list\n"
"5. Exit program\n")
ans = input("What would you like to do ? ").strip()
if ans == "1":
with open("items.txt", "r") as f:
print(f.read())
elif ans == "2":
i = int(input("How many items would you like to enter : "))
items = [input("Enter the name of item : ").lower() for i in range(i)]
with open("items.txt", "a") as f:
for item in items:
f.write("{}\n".format(item))
elif ans == "3":
with open("items.txt", "r+") as f:
f.truncate(0)
elif ans == "4":
i = int(input("How many items would you like to enter: ").lower())
items = [input("Enter the name of item and price: ").lower() for i in range(i)]
with open("items2.txt", "w") as f:
for item in items:
f.write("{}\n".format(item))
elif ans == "5":
leave = True
else:
print("Choose by entering either 1, 2, 3 or 4.")
To keep the program running until the user choose to close it you can use a while loop with a leave variable which takes the value True in case the user decides to quit the program by answering 5.
To open your files you should use the with statement.
That code works but it's not perfect because it does not give the user the choice to choose which file (list) to read and show on the screen so you can only have one list. To make it possible for the user to choose between the files you should use the os module.
Which brings us to that code :
import os
os.chdir("itemsFolder")
items = []
i = 0
leave = False
while leave is False:
print("Options:\n"
"1: View existing items\n"
"2: Add to list of items\n"
"3: Clear saved items\n"
"4: Make new list\n"
"5. Exit program\n")
ans = input("What would you like to do ? ").strip()
if ans == "1":
fileName = input("Which list would you like to consult : {} ".format(os.listdir()))
if os.path.exists(fileName):
with open(fileName, "r") as f:
print(f.read())
else:
print("No such list of item exists.")
elif ans == "2":
fileName = input("Which list would you like to consult : {} ".format(os.listdir()))
if os.path.exists(fileName):
i = int(input("How many items would you like to enter : "))
items = [input("Enter the name of item : ").lower() for i in range(i)]
with open(fileName, "a") as f:
for item in items:
f.write("{}\n".format(item))
else:
print("No such list of item exists.")
elif ans == "3":
fileName = input("Which list of items would you like to clear : {} ".format(os.listdir()))
if os.path.exists(fileName):
with open(fileName, "r+") as f:
f.truncate(0)
else:
print("No such list of item exists.")
elif ans == "4":
fileName = input("What do you want to call your new list : ").lower()
i = int(input("How many items would you like to enter: ").lower())
items = [input("Enter the name of item and price: ").lower() for i in range(i)]
with open(fileName + '.txt', "w") as f:
for item in items:
f.write("{}\n".format(item))
elif ans == "5":
leave = True
else:
print("Choose by entering either 1, 2, 3 or 4.")
You should use this tree structure in your project to use the code above :
ProjectFolder
|
-main.py
-itemsFolder

How can I get this program to loop indefinitely until the specific integer 4 is entered? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
This is a function of a larger Python program. How can I get it to loop continuously until "4" is entered? Any help is greatly appreciated.
print("\nEnter a number (1) - (4). (4) terminates the program.")
choice = int(input("Enter your choice: "))
while((choice != 1) and (choice != 2) and (choice != 3) and (choice != 4)):
choice = int(input("\nInvalid option. Enter a number from the menu: "))
if(choice == 1):
f = open("dna1.txt", "r")
if f.mode == "r":
contents = f.read()
print("\nOriginal: {0}" .format(contents))
if(choice == 2):
f = open("dna2.txt", "r")
if f.mode == "r":
contents = f.read()
print("\nOriginal: {0}" .format(contents))
if(choice == 3):
f = open("dna3.txt", "r")
if f.mode == "r":
contents = f.read()
print("\nOriginal: {0}" .format(contents))
if(choice == 4):
print("Exiting program.")
sys.exit
Just wrap all in a while True, also think about using elif as your choice will be one of all so don't to check the next one's if one successes, and you can simplify the while/choice using an array.
Also I'd suggest you refactor to avoid duplicate code (if you can) for the part that check mode, read file, save content, print content ;
while True:
while choice not in [1, 2, 3, 4]:
choice = int(input("\nInvalid option. Enter a number from the menu: "))
if choice == 1:
...
elif choice == 2:
...
elif choice == 3:
...
elif choice == 4:
print("Exiting program.")
sys.exit(1)
Or add an else at the end and remove the inner loop
while True:
choice = int(input(" Enter a number from the menu: "))
if choice == 1:
...
elif choice == 2:
...
elif choice == 3:
...
elif choice == 4:
print("Exiting program.")
sys.exit(1)
else:
print("\nInvalid option. Enter a number from the menu: ")
Have you tried using continue and break statement, I mean instead of saying condition in the while loop, you could say
while(True):
if(condition met):
break
elif(condition):
continue
You should probably add continue under all statements except the last on
You could improve this code, but as far as the question goes, simply wrap your initial loop into another loop.
print("\nEnter a number (1) - (4). (4) terminates the program.")
choice = int(input("Enter your choice: "))
while True:
while ((choice != 1) and (choice != 2) and (choice != 3) and (choice != 4)):
choice = int(input("\nInvalid option. Enter a number from the menu: "))
if (choice == 1):
f = open("dna1.txt", "r")
if f.mode == "r":
contents = f.read()
print("\nOriginal: {0}".format(contents))
if (choice == 2):
f = open("dna2.txt", "r")
if f.mode == "r":
contents = f.read()
print("\nOriginal: {0}".format(contents))
if (choice == 3):
f = open("dna3.txt", "r")
if f.mode == "r":
contents = f.read()
print("\nOriginal: {0}".format(contents))
if (choice == 4):
print("Exiting program.")
sys.exit(0)
You question has already been throughly answered by others.
However, I wanted to take a minute to show you a few opportunities for improving your coding style. I rewrote your program, and made some notes on how these changes can make your life easier as a developer.
Set constants to allow yourself to manipulate data on a single line instead of multiple places. - I did this by using an options variable for printing out the options to the user and for determining what to do with each option.
Make your loops as small as possible to increase readability. - In this example, I moved all of the logic that processes a choice out to a function. Now any reader can tell that all I'm really doing in this loop is (1) prompting the user, then (2) processing the choice.
Stick variables into strings - If there is only a small variation in a string that gets repeated, make the variation into a variable & drop it into the string. This will speed up your coding and make your code more readable. That's where choice comes in this example.
Use fstrings - This isn't a must, but it's a continuation of the previous point. Plus, it's a good way to optimize your code and make string parsing/concatenation more readable.
I hope this is helpful for you as you're learning Python! Happy coding!
options = list(range(1, 5))
finished = False
def process_choice(choice):
if choice not in options:
print("Invalid option.\n")
return False
if(choice == 4):
print("Exiting program.")
return True
with open(f"dna{choice}.txt", "r") as file:
contents = file.read()
print(f"\nOriginal: {contents}")
return True
print(f"\nEnter a number {options}. (4) terminates the program.\n")
while not finished:
choice = input("Enter a number from the menu: ")
finished = process_choice(int(choice))
This problem can be resolved with basic indention in python 3 but you can also modify this like:
# continues loop until specific key is pressed
choice=int(input("\nEnter a number (1) - (4). (4) terminates the program."))
while choice <= 4 :
choice=int(input("\nInvalid option. Enter a number from the menu: "))
if choice == 1 :
f = open("dna1.txt", "r")
if f.mode == "r":
contents = f.read()
print("\nOriginal: {0}" .format(contents))
elif choice == 2 :
f = open("dna2.txt", "r")
if f.mode == "r":
contents = f.read()
print("\nOriginal: {0}" .format(contents))
elif choice == 3 :
f = open("dna3.txt", "r")
if f.mode == "r":
contents = f.read()
print("\nOriginal: {0}" .format(contents))
else :
print("Exiting program.")
sys.exit

How to have python recognize correct value in my code? Dictionaries

for i in range(n):
while len(dictionary)>0:
choice = random.choice(list(dictionary.keys()))
correctAnswer = dictionary[choice]
print("English: ",choice)
guess = input("Spanish: ")
dictionary.pop(choice)
if guess == correctAnswer:
print("\nCorrect!\n")
else:
print("Incorrect\n")
wrongAnswers.append(choice)
break
print("\nYou missed", len(wrongAnswers), "words\n")
Hi, I am trying to create a vocabulary test on python. My code works up until this chunk. After the program prompts the user for their guess, the program will say it is incorrect even if it is the right answer. Is there an error in this code? How can I get around this?
This is what it looks like:
English: white
Spanish: blanco
Incorrect
English: purple
Spanish: morado
Incorrect
Thanks!
Full Code:
def main():
import random
wrongAnswers = []
print("Hello, Welcome to the Spanish-English vocabulary test.")
print(" ")
print("\nAfter the test, this program will create a file of the incorrect answers for you to view")
print("\nTo start, please select from the following options: \nverbs.txt \nadjectives.txt \ncolors.txt \nschool.txt \nplaces.txt") #sk
while True: #SK
selection = input("Insert your selection: ").lower() #user inputs selection #sk
if selection == "verbs.txt" or selection == "adjectives.txt" or selection == 'colors.txt' or selection == 'school.txt' or selection == 'places.txt':
print("You have chosen", selection, "to be tested on.")
break
if False:
print("try again.")
selection = input("Insert your selection: ").lower()
break
file = open(selection, 'r')
dictionary = {}
with file as f:
for line in f:
items = line.rstrip("\n").split(",")
key, values = items[0], items[1:]
dictionary[key] = values
length = len(dictionary)
print(length,'entries found')
n= int(input("How many words would you like to be tested on: "))
while n > length:
print("Invalid. There are only" ,length, "entries")
n= int(input("How many words would you like to be tested on: "))
print("You have chosen to be tested on",n, "words.\n")
for i in range(n):
while len(dictionary)>0:
choice = random.choice(list(dictionary.keys()))
correctAnswer = dictionary[choice]
print("English: ",choice)
guess = input("Spanish: ")
dictionary.pop(choice)
if guess == correctAnswer:
print("\nCorrect!\n")
else:
print("Incorrect\n")
wrongAnswers.append(choice)
break
print("\nYou missed", len(wrongAnswers), "words\n")
if len(wrongAnswers) > 0:
wrong = str(wrongAnswers)
output = input("Please name the file you would like you wrong answers to be saved in: ")
outf = open(output, 'w')
outf.write(wrong)
outf.close()
else:
print("You got all of the problems correct!")
main()

Writing to a file help in python 2.7

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()

Categories

Resources