I'm currently working on an small banking application in python. I created functions that opens a txt file. I tested the function on its own so I know it works, however when implemented alongside the menu it seems not to work.
def parse_in():
with open('bank.txt', 'r') as details:
lines = details.read().splitlines()
return lines
Later on I have a simple menu with few options but here I will only show the one I'm having issues with.
def menu():
print("Please selected one of the options" + "\n\t1: Open account"
while True:
try:
selection = int(input("Please enter your choice: "))
if selection == 1:
open_account(details)
else:
break
except:
print("Please enter number 1-6")
if 1 is selected an open account should be ran
def open_account(details):
print("Welcome to your new account")
new_account_number = randint(000000, 999999)
while True:
try:
new_account_balance = float(input("Enter your sum of money: "))
if new_account_balance < 0:
print("please enter positive value")
else:
break
except:
print("Please Enter Number Only")
while True:
new_account_name = input("Enter your name: ")
if " " in new_account_name:
print("Please enter your full name")
else:
break
details.append(new_account_number)
details.append(new_account_balance)
details.append(new_account_name)
After the information was imputed the idea is that they're suppose to save to the same file using a function.
def parse_out(details):
with open('bank.txt', 'w') as file:
for i in details:
file.write(str(i) + '\n')
and everything is ran in main function
def main():
details = parse_in()
welcome()
menu()
parse_out(details)
When I press 1 the open account function seems not be running instead, the menu loops back to choosing one of the options. I'n not really sure why it does that as it seems it should run and take information from user fallowed by saving the info to file.
Related
I am trying to create a registrar system through Python with pickles. I have gotten the system to record user input, but it does not save it for future implementations of the program.
Here is the code that will start the program:
import datetime
import pandas as pd
import pickle as pck
import pathlib
from pathlib import *
from registrar import *
prompt = "Please select an option: \n 1 Create a new course \n 2 Schedule a new course offering \n 3 List this school's course catalogue \n 4 List this school's course schedule \n 5 Hire an instructor \n 6 Assign an instructor to a course \n 7 Enroll a student \n 8 Register a student for a course \n 9 List this school's enrolled students \n 10 List the students that are registered for a course \n 11 Submit a student's grade \n 12 Get student records \n 13 Exit"
farewell = "Thank you for using the Universal University Registrar System. Goodbye!"
print ("Welcome to the Universal University Registration System.")
print ("\n")
try: #As long as CTRL-C has not been pressed, or 13 not been input by user.
input_invalid = True
while input_invalid:
inst = input("Please enter the name of your institution. ").strip()
domain = input("Please enter the domain. ").strip().lower()
if inst == "" or domain == "":
print("Your entry is invalid. Try again.")
else:
input_invalid = False
schoolie = Institution(inst, domain)
if Path(inst + '.pkl').exists() == False:
with open(inst + '.pkl', 'r+b') as iptschool:
schoolie = pck.load(iptschool)
while True:
print (prompt)
user_input = input("Please enter your choice: ")
try:
user_input = int(user_input)
if user_input < 1 or user_input > 14: #UserInput 14: on prompt.
raise ValueError("Please enter a number between 1 and 13, as indicated in the menu.")
except ValueError:
print("Not a valid number. Please try again.")
if user_input == 1: #Create a new course
input_invalid2 = True #Ensure that the user actually provides the input.
while input_invalid2:
input_name = input("Please enter a course name: ").strip()
input_department = input("Please enter the course's department: ").strip()
input_number = input("Please enter the course's number (just the number, not the departmental prefix): ").strip()
try:
input_number = int(input_number)
except ValueError:
print ("Please print an integer. Try again.")
input_credits = input("Please enter the number of credits awarded for passing this course. Please use an integer: ").strip()
try:
input_credits = int(input_credits)
except ValueError:
print ("Please print an integer. Try again.")
if input_name != "" and input_department != "" and input_number and input_credits:
input_invalid2 = False #Valid input
else:
print("One or more of your entries is invalid. Try again.")
added_course = Course(input_name, input_department, input_number, input_credits)
for course in schoolie.course_catalog:
if course.department == input_department and course.number == input_number and course.name == input_name:
print("That course is already in the system. Try again.")
input_invalid2 == True
if input_invalid2 == False:
schoolie.add_course(added_course)
print ("You have added course %s %s: %s, worth %d credits."%(input_department,input_number,input_name, input_credits))
And here is the second option, which SHOULD reveal that it is stored, but it does not.
elif user_input == 2: #Schedule a course offering
input_invalid2 = True #Ensure that the user actually provides the input.
while input_invalid2:
input_department = input("Please input the course's department: ").strip()
input_number = input("Please input the course's number: ").strip()
course = None
courseFound = False
for c in schoolie.course_catalog:
if c.department == input_department and c.number == input_number: #Course found in records
courseFound = True
course = c
input_section_number = input("Please enter a section number for this course offering: ").strip()
input_instructor = input("If you would like, please enter an instructor for this course offering: ").strip()
input_year = input("Please enter a year for this course offering: ").strip()
input_quarter = input("Please enter the quarter in which this course offering will be held - either SPRING, SUMMER, FALL, or WINTER: ").strip().upper()
if input_course != "" and input_course in schoolie.course_catalog and input_section_number.isdigit() and input_year.isdigit() and input_quarter in ['SPRING', 'SUMMER', 'FALL', 'WINTER'] and input_credits.isdigit():
if input_instructor != "": #Instructor to be added later, if user chooses option 6.
added_course_offering = CourseOffering(c, input_section_number, None, input_year, input_quarter)
else:
added_course_offering = CourseOffering(c, input_section_number, input_instructor, input_year, input_quarter)
schoolie.add_course_offering(added_course_offering)
input_invalid2 = False #Valid input
print ("You have added course %s, Section %d: %s, worth %d credits."%(input_course,input_section_number,input_name, input_credits))
else:
print("One or more of your entries is invalid. Try again.")
if courseFound == False: #If course has not been found at the end of the loop:
print("The course is not in our system. Please create it before you add an offering.")
break
By the way, I think I have the system closing properly. Correct me if I'm wrong:
elif user_input == 13: #Exit
with open(inst + '.pkl', 'wb') as output:
pck.dump(schoolie, output, pck.HIGHEST_PROTOCOL)
del schoolie
print (farewell)
sys.exit()
except KeyboardInterrupt: #user pushes Ctrl-C to end the program
print(farewell)
I believe that there is something wrong with the way that I am setting up the pickles files. I'm creating them, but I seem not to be putting data into them.
I apologize for the long-winded nature of this question, but I hope that the details will help you understand the problems that I've been having. Thanks in advance for the help!
it seems you may have dump and load reversed: (from the docs)
Signature: pck.load(file, *, fix_imports=True, encoding='ASCII', errors='strict')
Docstring:
Read and return an object from the pickle data stored in a file.
Signature: pck.dump(obj, file, protocol=None, *, fix_imports=True)
Docstring:
Write a pickled representation of obj to the open file object file.
With all those lines of code, it does get a little confusing, but I don't see any code that is pickling and writing the objects to a file.
Before anything else, you should assign the file to a variable so you can reference it. To do this, you'll have code similar to this:MyFile = open("FileName.extension","wb"). MyFile can be any name you want, it will be what you use later to reference the file. FileName is the name of the file itself. This is the name it will have in File Explorer. .extension is the file's extension, specifying the type of file. You should use .dat for this. wb is the file access mode. "w" means write, and "b" means binary. (Pickled objects can only be stored in a binary file.)
To write the pickled objects, you'll need this code:pck.dump(object,MyFile). (Usually, you would use pickle.dump(object,MyFile), but you imported pickle as pck.)
After writing the data to the file, you'll want to retrieve it. To do this, the "wb" instance of MyFile needs to be closed like this:MyFile.close(). Then you'll need to re-open the file in read mode using the following code:MyFile = open("FileName.extension","rb") Then you would use this:object = pickle.load(MyFile) to read the data. In the preceding example, (the load function), your object must have the same name as when you pickled it using the dump function. (pck.dump(object,MyFile))
In the end, you'll end up with something similar to this:
if writing conditions are true:
MyFile = open("FileName.dat","wb")
pickle.dump(object,MyFile) # This will be repeated for each object.
MyFile.close()
if reading conditions are true:
MyFile = open("FileName.dat","rb")
object = pickle.load(MyFile) # This will be repeated for each object.
MyFile.close()
I'm sorry if this wasn't the answer you wanted. Because of all those lines of code, it is somewhat hard to understand. I need clarification to give a better answer.
I am trying to finish off my program my adding a menu that allows the user to select a few options that allow the user to store website names and passwords in lists. But there was a problem as soon as I have appended some website names and passwords into their respective vaults where whenn I try to select an option after appending the website names and passwords, "1" for example is the expected input to call the viewapp() function to see the websites and passwords stored so far. The thing is it takes more than twice to call the viewapp() function, where it rejects the first expected input but accepts the 2nd one strangely. Also when I select the 3rd option for the purpose to call summary(), the whole printed summary would print out twice, which is a similar pattern to the menu only accepting the 2nd expected input. The program is doing what I want except for this annoying bug where selecting those four options makes it ask for input a second time when it's supposed to straight away jump to that function. Help would be appreciated.
appvault = []
passvault = []
def logged():
print("----------------------------------------------------------------------\n")
print("Hello, welcome to the password vault console. ")
modea = input("""Below are the options you can choose from in the password vault console:
##########################################################################\n
1) Find the password for an existing webiste/app
2) Add a new website/app and a new password for it
3) Summary of the password vault
4) Exit
##########################################################################\n
> """).strip()
return modea
def viewapp():
if len(appvault) > 0:
for app in appvault:
print("Here is the website/app you have stored:")
print("- {}\n".format(app))
if len(passvault) > 0 :
for code in passvault:
print("Here is the password you have stored for the website/app: ")
print("- {}\n".format(code))
else:
print("You have no apps or passwords entered yet!")
def addapp():
while True:
validapp = True
while validapp:
new_app = input("Enter the new website/app name: ").strip().lower()
if len(new_app) > 20:
print("Please enter a new website/app name no more than 20 characters: ")
elif len(new_app) < 1:
print("Please enter a valid new website/app name: ")
else:
validapp = False
appvault.append(new_app)
validnewpass = True
while validnewpass:
new_pass = input("Enter a new password to be stored in the passsword vault: ")
if not new_pass.isalnum():
print("Your password for the website/app cannot be null, contain spaces or contain symbols \n")
elif len(new_pass) < 8:
print("Your new password must be at least 8 characters long: ")
elif len(new_pass) > 20:
print("Your new password cannot be over 20 characters long: ")
else:
validnewpass = False
passvault.append(new_pass)
validquit = True
while validquit:
quit = input("\nEnter 'end' to exit or any key to continue to add more website/app names and passwords for them: \n> ")
if quit in ["end", "End", "END"]:
logged()
else:
validquit = False
addapp()
return addapp
def summary():
if len(passvault) > 0:
for passw in passvault:
print("----------------------------------------------------------------------")
print("Here is a summary of the passwords stored in the password vault:\n")
print("The number of passwords stored:", len(passvault))
print("Passwords with the longest characters: ", max(new_pass for (new_pass) in passvault))
print("Passwords with the shortest charactrs: ", min(new_pass for (new_pass) in passvault))
print("----------------------------------------------------------------------")
else:
print("You have no passwords entered yet!")
while True:
chosen_option = logged()
print(chosen_option)
if chosen_option == "1":
viewapp()
elif chosen_option == "2":
addapp()
elif chosen_option == "3":
summary()
elif chosen_option == "4":
break
else:
print("That was not a valid option, please try again: ")
print("Goodbye")
This happens because you call logged() when exiting addapp():
if quit in ["end", "End", "END"]:
logged()
Then, the choice you enter is returned by logged(), and thrown away as it isn't assigned to anything.
You're now back at the end of the previous block in addapp(), and the next instruction is return addapp, that will bring you back to your main loop, where you'll be sent to logged() again by chosen_option = logged()
Note that in return addapp, you return the addapp function itself, which is certainly not what you want to do. So, as you don't need a return value for addapp(), just use return, or nothing at all, Python will automatically return at the end of the function.
So, to solve your problem: directly return when you're done entering sites:
if quit in ["end", "End", "END"]:
return
Note also that you recursively call addapp() from itself when you add more sites.
You should generaly avoid that unless you really want to use some recursive algorithm, and rather use a loop as you did in your main loop. By default, Python limits you to 1000 recursion levels - so you could even crash your app by entering more than 1000 sites in a row ;)
The summary problem is only caused by the unnecessary for loop in summary()
You are nearly there. The issue is in the addapp() function at line 63:
if quit not in ["end", "End", "END"]:
logged()
if you replace
logged()
with
pass
Then everything will work a ok.
You are not handling the result of the logged function here anyway.
You also do not need to process the logged function here. The addapp will exit and the logged function will be called and handled in the while loop the addapp function was called from.
I am currently trying to make a program where the user can create sets of data, but I am having a difficult time figuring out how to handle the user picking the user picking a name out of a list of files to edit or view.
Here is how I display the files they can choose from. How can I easily allow them to choose any one of the available files without hardcoding each individual one?
available_files = os.listdir('./DSC_Saves/')
print(available_files)
user_input = input('File Name: ')
What I would like to avoid doing is the following:
if user_input == available_files[0]:
#do action
elif user_input == available_files[1]:
#do action 2
elif user_input == available_files[2]:
#do action 3
As mentioned, you can do this by using in on the list of available files as follows:
available_files = os.listdir('./DSC_Saves/')
print(available_files)
while True:
user_input = input('File name: ')
if user_input in available_files:
break
print("You have selected '{}'".format(user_input))
Alternatively, to make it easier to type, you could present the user with a numeric menu to choose from as follows:
available_files = os.listdir('./DSC_Saves/')
for index, file_name in enumerate(available_files, start=1):
print('{:2} {}'.format(index, file_name))
while True:
try:
user_input = int(input('Please select a file number: '))
if 1 <= user_input <= len(available_files):
selected_file = available_files[user_input-1]
break
except ValueError as e:
pass
print("You have selected '{}'".format(selected_file))
Both solutions will continue prompting until a valid file name has been entered.
So for example you could see the following output:
1 test1.txt
2 test2.txt
Please select a file number: 3
Please select a file number: 2
You have selected 'test2.txt'
I am extremely new to Python, and to programming in general, so I decided to write some basic code to help me learn the ins and outs of it. I decided to try making a database editor, and have developed the following code:
name = []
rank = []
age = []
cmd = input("Please enter a command: ")
def recall(item): #Prints all of the information for an individual when given his/her name
if item in name:
index = name.index(item) #Finds the position of the given name
print(name[index] + ", " + rank[index] + ", " + age[index]) #prints the element of every list with the position of the name used as input
else:
print("Invalid input. Please enter a valid input.")
def operation(cmd):
while cmd != "end":
if cmd == "recall":
print(name)
item = input("Please enter an input: ")
recall(item)
elif cmd == "add":
new_name = input("Please enter a new name: ")
name.append(new_name)
new_rank = input("Please enter a new rank: ")
rank.append(new_rank)
new_age = input("Please input new age: ")
age.append(new_age)
recall(new_name)
else:
print("Please input a valid command.")
else:
input("Press enter to quit.")
operation(cmd)
I want to be able to call operation(cmd), and from it be able to call as many functions/perform as many actions as I want. Unfortunately, it just infinitely prints one of the outcomes instead of letting me put in multiple commands.
How can I change this function so that I can call operation(cmd) once, and call the other functions repeatedly? Or is there a better way to go about doing this? Please keep in mind I am a beginner and just trying to learn, not a developer.
Take a look at your code:
while cmd != "end":
if cmd == "recall":
If you call operation with anything than "end", "recall" or "add", the condition within while is True, the next if is also True, but the subsequent ifs are false. Therefore, the function executes the following block
else:
print("Please input a valid command.")
and the while loop continues to its next lap. Since cmd hasn't changed, the same process continues over and over again.
You have not put anything in your code to show where operator_1, operator_2, and operator_3 come from, though you have hinted that operator_3 comes from the commandline.
You need to have some code to get the next value for "operator_3". This might be from a list of parameters to function_3, in which case you would get:
def function_3(operator_3):
for loopvariable in operator_3:
if loopvariable == some_value_1:
#(and so forth, then:)
function_3(["this","that","something","something else"])
Or, you might get it from input (by default, the keyboard):
def function_3():
read_from_keyboard=raw_input("First command:")
while (read_from_keyboard != "end"):
if read_from_keyboard == some_value_1:
#(and so forth, then at the end of your while loop, read the next line)
read_from_keyboard = raw_input("Next command:")
The problem is you only check operator_3 once in function_3, the second time you ask the user for an operator, you don't store its value, which is why its only running with one condition.
def function_3(operator_3):
while operator_3 != "end":
if operator_3 == some_value_1
function_1(operator_1)
elif operator_3 == some_value_2
function_2
else:
print("Enter valid operator.") # Here, the value of the input is lost
The logic you are trying to implement is the following:
Ask the user for some input.
Call function_3 with this input.
If the input is not end, run either function_1 or function_2.
Start again from step 1
However, you are missing #4 above, where you are trying to restart the loop again.
To fix this, make sure you store the value entered by the user when you prompt them for an operator. To do that, use the input function if you are using Python3, or raw_input if you are using Python2. These functions prompt the user for some input and then return that input to your program:
def function_3(operator_3):
while operator_3 != 'end':
if operator_3 == some_value_1:
function_1(operator_3)
elif operator_3 == some_value_2:
function_2(operator_3)
else:
operator_3 = input('Enter valid operator: ')
operator_3 = input('Enter operator or "end" to quit: ')
looks like you are trying to get input from the user, but you never implemented it in function_3...
def function_3(from_user):
while (from_user != "end"):
from_user = raw_input("enter a command: ")
if from_user == some_value_1:
# etc...
I am slightly stuck on my code. My knowledge of python is very limited but I am trying to quit the loop to display the items someone selects. I have tried if statements that don't work. Considered a def statement but not too sure how to implement it and Return is an idea but obviously needs the def statement to work.
Any help is much appreciated.
P.S I have no idea how to upload the CSV file but, the following link is what I am aiming to do: https://dl.dropboxusercontent.com/u/31895483/teaching%20delivered/FE/2013-14/Access%20-%20Prg/assignment/menu2.swf
import csv
f = open("menu.csv", "r") #Has items for the menu and is read only
spent = 0
order = []
menu = []
for line in f:
line = line.rstrip("\n")
dish = line.split(',')
menu = menu + [dish]
f.close()
#Menu imported into python, no need to leave file open
while True:
dishes = -1
for dish in menu:
if dishes == -1:
print ("Dish No".ljust(10), end="")
else:
print(str(dishes).ljust(10), end="")
print(dish[0].ljust(15), end="")
print(dish[1].ljust(30), end="")
print(dish[2].ljust(15), end="")
print(dish[3], end="\n\n")
dishes += 1
reply = input("Please choose your first item: ")
print()
spent = spent + float(menu[int(reply)+1][2])
order = order + [reply]
print(len(order), "choices made so far =", order, "and cost = £ ", spent)
print()
print ("Please choose an item from the menu (0-9 or press Q to end): ")
print()
All you need to do is check for the exit condition, and then use the break statement to break out of the loop.
while True:
# other stuff here
reply = input("Please choose a menu item:")
if reply.upper() == 'Q':
break # Break out of the while loop.
# We didn't break, so now we can try to parse the input to an integer.
spent = spent + float(menu[int(reply)+1][2])
This pattern of while True + other_code + if condition: break is pretty common, which has at least two benefits:
You're using accepted idioms, so you'll recognize them when you encounter them elsewhere.
Other people (including your future self) will be able to understand your code when they read it.
a cool trick that I like
my_menu_choices = iter(lambda : input("Please choose a menu item:").lower(),"q")
for i,dish in dishes:
print("%d. %s"%(i,dish))
print("Q. type q to QUIT")
my_menu_choices = list(my_menu_choices)
print("You Choose: %s"%my_menu_choices)