I am trying to solve the same a problem that does the following...
Create a program that stores Employee objects in a dictionary. Use the employee ID number as the key. The program should present a menu that lets the user perform the following actions:
Look up an employee in the dictionary
Add a new employee to the dictionary
Change an existing employee’s name, department, and job title in the
dictionary
Delete an employee from the dictionary
Quit the program
When the program ends, it should pickle the dictionary and save it to a file. Each time the program starts, it should try to load the pickled dictionary from the file. If the file does not exist, the program should start with an empty dictionary.
I found another user that posted the question here but I am having some different problems.
How should I quit the program? I tried break but it failed
miserably.
I know my formatting is atrocious but I can't figure out where it is
going wrong.
Here is what I have so far:
def main():
if os.path.exists("employee.dat"):
file = open("employee.dat","rb")
employee_dictionary = pickle.load(file)
file.close()
else:
emp1 = Employee("Susan Myers", 47899, "Accounting", "Vice President")
emp2 = Employee("Mark Jones", 39119, "IT", "Programmer")
emp3 = Employee("Joy Rogers", 81774, "Manufacturing", "Engineer")
employee_dictionary = {emp1.get_ID_number(): emp1.get_name()+ '' + emp1.get_dept()+ '' + emp1.get_job_title(),\
emp2.get_ID_number(): emp2.get_name()+ '' + emp2.get_dept()+ '' + emp2.get_job_title(),\
emp3.get_ID_number(): emp3.get_name()+ '' + emp3.get_dept()+ '' + emp3.get_job_title()}
#should I add another function here to call the employee_dictionary?
choice = 'y'
while choice.upper()== 'Y':
print("Make a selection from the following actions:")
print("Lookup an employee in the dictionary: 1")
print("Add a new employee to the dictionary: 2")
print("Change an existing employee's name, department, and job title in the dictionary: 3")
print("Delete an employee from the dictionary: 4")
print("Quit the program: 5")
selection = input("Make your selection: ")
if int(selection) == 1:
id_number = input("What is the employee's ID number?")
if int(id_number) in employee_dictionary.keys():
print(employee_dictionary[int(id_number)])
else:
print("The employee does not exist.")
else:
if int(selection) == 2:
id_number = input("What is the employee's ID number?")
if int(id_number) in employee_dictionary.keys():
print('That employee already exists.')
else:
name = input("Enter the name of the employee:")
dept = input("Enter the department of the employee:")
title = input("Enter the job title of the employee:")
emp4 = Employee(name,int(id_number), dept, title)
employee_dictionary[emp4.get_ID_number()]= emp1.get_name()+ '' + emp4.get_dept()+ '' + emp4.get_job_title()
print("The employee was added.")
else:
if int(selection) == 3:
id_number = input("What is the employee's ID number?")
if int(id_number) in employee_dictionary.keys():
name = input("Enter the name of the employee:")
dept = input("Enter the department of the employee:")
title = input("Enter the job title of the employee:")
emp4 = Employee(name,int(id_number), dept, title)
employee_dictionary[emp4.get_ID_number()]= emp1.get_name()+ '' + emp4.get_dept()+ '' + emp4.get_job_title()
print("The employee record has been updated.")
else:
print("Record not found.")
else:
if int(selection) == 4:
id_number = input("What is the employee's ID number?")
print("Deleted: ", employee_dictionary.pop(int(id_number),"Record not found."))
else:
if int(selection)!=5:
print("")
#break
choice = input("Do you want to make another selection (y or n)?")
file = open('employee.dat','wb')
pickle.dump(employee_dictionary,file)
file.close()
main()
Related
import re
contact = {}
def display_contact():
for name, number in sorted((k,v) for k, v in contact.items()):
print(f'Name: {name}, Number: {number}')
#def display_contact():
# print("Name\t\tContact Number")
# for key in contact:
# print("{}\t\t{}".format(key,contact.get(key)))
while True:
choice = int(input(" 1. Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit contact \n 5. Delete contact \n 6. Save your contact as a file \n 7. Update Saved List \n 8. Exit \n Your choice: "))
if choice == 1:
while True:
name = input("Enter the contact name ")
if re.fullmatch(r'[a-zA-Z]+', name):
break
while True:
try:
phone = int(input("Enter number "))
except ValueError:
print("Sorry you can only enter a phone number")
continue
else:
break
contact[name] = phone
elif choice == 2:
search_name = input("Enter contact name ")
if search_name in contact:
print(search_name, "'s contact number is ", contact[search_name])
else:
print("Name is not found in contact book")
elif choice == 3:
if not contact:
print("Empty Phonebook")
else:
display_contact()
elif choice == 4:
edit_contact = input("Enter the contact to be edited ")
if edit_contact in contact:
phone = input("Enter number")
contact[edit_contact]=phone
print("Contact Updated")
display_contact()
else:
print("Name is not found in contact book")
elif choice == 5:
del_contact = input("Enter the contact to be deleted ")
if del_contact in contact:
confirm = input("Do you want to delete this contact Yes or No? ")
if confirm == 'Yes' or confirm == 'yes':
contact.pop(del_contact)
display_contact
else:
print("Name is not found in phone book")
elif choice == 6:
confirm = input("Do you want to save your contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
with open('contact_list.txt','w') as file:
file.write(str(contact))
print("Your contact-book is saved!")
else:
print("Your contact book was not saved.")
# else:
elif choice == 7:
confirm = input("Do you want to update your saved contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
f = open("Saved_Contact_List.txt" , "a")
f.write("Name = " + str(name))
f.write(" Number = " + str(phone))
f.close()
#with open('contact_list.txt','a') as file:
# file.write(str(contact))
print("Your contact-book has been updated!")
else:
print("Your contact book was not updated.")
else:
break
I have tried but only get to save the last input and not all of the contact list. Any ideas on how to save them all. I have been trying different code as I have comment some out to try a different way but it only print the last input. I would like it to save a output file with the first save to save all the contact then if they add or update a contact to save it as a updated saved file like choice 7. But I only get it to save the last input. I still learning how python works and this is over my head.
You're looking for serialization, which is (usually) best left to libraries. The json library easily handles reading and writing dictionaries to a file.
To write a dictionary, take a look at json.dump():
with open("Saved_Contact_List.txt", "w") as f:
json.dump(contact, f)
New to programming and trying to learn how to store data using pickle. Essentially, what I'm trying to do is create an address book using classes stored in a dictionary. I define the class (Contact). It all worked, but when I tried to introduce pickling to store data from a previous session, I've created 2 errors that I've found so far.
1: If I select to load a previous address book, I cant update or view the class variables. It's almost like there are two different dictionaries.
2: I select not to load a previous address book and add a contact. When I add the contact and try to view the contacts, I'll get an "Unbound Error: local variable 'address book' referenced before assignment"
What am I doing wrong with pickling?
address_book= {}
class Contact:
def __init__(self,first_name,last_name, phone,company):
self.first_name = first_name
self.last_name = last_name
self.phone = phone
self.company = company
def __call__(self):
print("Contact: %s \nPhone #: %s \nCompany: %s" %(self.name,self.phone,self.company))
def erase(entry):
del address_book[entry] # delete address book entry
del entry #delete class instance
def save():
new_file = open("addressBook.pkl", "wb")
saved_address = pickle.dump(address_book, new_file)
new_file.close()
def load():
open_file = open("addressBook.pkl", "rb")
address_book = pickle.load(open_file)
open_file.close()
print(address_book)
return address_book
def add_contact():
first_name = input("Please type the first name of the contact. ")
last_name = input("Please type in the last name of the contact. ")
if " " in first_name or " " in last_name:
print("Please do not add spaces to your first or last name.")
else:
phone = input("Please type the user phone number without hyphens. ")
if not phone.isnumeric():
print("That isn't a valid phone number.")
else:
company = input("Please type the company they work for. ")
contact = Contact(first_name,last_name,phone,company)
address_book[first_name + " " +last_name] = contact #assign key[first and last name] to value[the class instance] in dictionary
def view_contact(entry):
if entry in address_book:
print("First Name: %s" %(address_book[entry].first_name)) #get class variables
print("Last Name: %s" %(address_book[entry].last_name))
print("Phone Number: %s" %(address_book[entry].phone))
print("Company: %s" %(address_book[entry].company))
else:
print("That person isn't in your address book")
def update(entry):
if entry in address_book:
update_choice = input("Would you like to update the first name (f), last name (l), phone (p), or company (c)? ").lower()
if update_choice == "f":
address_book[entry].first_name = input("Please type the updated first name of this contact. ")
updated_key = address_book[entry].first_name + " " + address_book[entry].last_name
address_book[updated_key] = address_book[entry]
del address_book[entry] #delete old key
elif update_choice == "l": #update last name
address_book[entry].last_name = input("Please type the updated last name of this contact. ")
updated_key = address_book[entry].first_name + " " + address_book[entry].last_name
address_book[updated_key] = address_book[entry]
del address_book[entry]
elif update_choice == "p":
address_book[entry].phone = input("Please type the updated phone number of this contact. ")
elif update_choice == "c":
address_book[entry].company = input("Please type the updated company of this contact. ")
else:
print("That was not valid. Please try again.")
def main():
print("Welcome to your address book!!")
returning_user = input("Would you like to load a previous address book? Y or N ").lower()
if returning_user == "y":
address_book = load()
while True:
choice = input("Please type A:Add, B:View All Contacts, V:View a Contact, D:Delete, U:Update, or X:Exit ").lower()
if choice == "x":
break
elif choice == "a":
add_contact()
elif choice == "b":
if len(address_book) == 0: #error check if no contacts
print("You don't have any friends. PLease go make some and try again later. :(")
else:
for i in address_book:
print(i)
elif choice == "v":
if len(address_book) == 0:
print("You don't have any friends. PLease go make some and try again later. :(")
else:
view = input("Who do you want to view? Please type in their first and last name. ")
view_contact(view)
elif choice == "d":
if len(address_book) == 0:
print("You don't have any friends. PLease go make some and try again later. :(")
else:
contact = input("Please type the first and last name of the person you want to delete ")
if contact in address_book:
erase(contact)
elif choice == "u":
if len(address_book) == 0:
print ("C'mon, you don't know anyone yet. How about you make some friends first?")
else:
choice = input("What is the first and last name of the person you'd like to update? ")
update(choice)
else:
print("That was not valid. Please try again.")
print()
save_book = input("Would you like to save your book? Y or N ").lower()
if save_book == "y":
save()
print("Thanks for using the address book!")
main()
MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []
# And another function here for the user menu
selection = input(MENU_PROMPT)
def movie_data():
title = input("Enter the movie title: ")
director = input("Enter the movie director: ")
year = input("Enter the movie release year: ")
movies.append({
'title': title,
'director': director,
'year': year
})
def display():
print("movies =", end =" ")
for movie in movies:
print(movie['title'])
while selection != 'q':
if selection == "a":
movie_data()
elif selection == "l":
display()
elif selection == "f":
find = input("enter the movie title")
if find in movies:
print("movie found.", movies)
else:
print(f'No Such Movie, Named {find}, Found!, Try Other Movie Name.')
else:
print('Unknown command. Please try again.')
selection = input(MENU_PROMPT)
if the user inputs the f for finding the movie name in the movies dictionary then what do I write in the last elif function, can anyone explain it??
I want - (userinput movie name) - avengers
output - match found! movie name - avengers, director - (what the userinputs) & year - (what the userinputs)
You can make a search function which iterates over each element in the list and searches for the title attribute in dictionary.
MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []
# And another function here for the user menu
selection = input(MENU_PROMPT)
def movie_data():
title = input("Enter the movie title: ")
director = input("Enter the movie director: ")
year = input("Enter the movie release year: ")
movies.append({
'title': title,
'director': director,
'year': year
})
def display():
print("movies =", end =" ")
for movie in movies:
print(movie['title'])
def search(title):
for i in range(len(movies)):
if(movies[i]['title']== str(title)):
return movies[i]
return None
while selection != 'q':
if selection == "a":
movie_data()
elif selection == "l":
display()
elif selection == "f":
find = input("enter the movie title:")
movie = search(find)
if (movie):
print("movie found:", movie)
else:
print(f'No Such Movie, Named {find}, Found!, Try Other Movie Name.')
else:
print('Unknown command. Please try again.')
selection = input(MENU_PROMPT)
You have a list with dictionaries that contain title, director and year keys. You can loop through the list and search a match for the title, assuming the user inputs the title:
movies.append({
'title': "title",
'director': "director",
'year': "year"
})
for m in movies:
if m.get('title').lower().find("title") > -1:
print("true")
else:
print("false")
Total beginner question, from what I can gather I've managed to assign a string incorrectly, but I can't see where I've gone wrong.
Any help would be appreciated, code below:
students = []
def add_student(name, student_id):
student = {"name": name, "student_id": student_id}
students.append(student)
while 1 == 1:
try:
add_student = input("Do you wish to enter the name of a Student (Yes/No)?")
if add_student == "Yes":
student_name = input("Enter student name: ")
print(student_name)
student_id = input("Enter student ID: ")
print(student_id)
print(student_name + ' ' + student_id)
add_student(student_name, student_id)
print(student_name+' '+student_id)
print(*students)
elif add_student == "No":
break
else:
print("Invalid answer 1")
except KeyError:
print("Invalid answer 2")
print(*students)
You've called the function def add_student(...) and the variable add_student = .... How is the interpreter supposed to know you want the function when the variable is called that?
In fact, you've overwitten the function. By the time you call it, it no longer exists. Rename the variable or function to something else. I'll let the comments help you with certain other issues (global lists...) in your code.
your function and local variable name same
students = []
def add_student_data(name, student_id):
student = {"name": name, "student_id": student_id}
students.append(student)
while 1 == 1:
try:
add_student = input("Do you wish to enter the name of a Student (Yes/No)?")
if add_student == "Yes":
student_name = input("Enter student name: ")
print(student_name)
student_id = input("Enter student ID: ")
print(student_id)
print(student_name + ' ' + student_id)
add_student_data(student_name, student_id)
print(student_name+' '+student_id)
print(*students)
elif add_student == "No":
break
else:
print("Invalid answer 1")
except KeyError:
print("Invalid answer 2")
print(*students)
The name of the method def add_student(name, student_id) and the name of the variable add_student = input("Do you wish to enter the name of a Student (Yes/No)?") is the same.
It exist a similar question here.
You have to change the name of one of then.
students = []
def add_student(name, student_id):
student = {"name": name, "student_id": student_id}
students.append(student)
while 1 == 1:
try:
user_respond = raw_input("Do you wish to enter the name of a Student (Yes/No)?")
if user_respond == "Yes":
student_name = raw_input("Enter student name: ")
print(student_name)
student_id = raw_input("Enter student ID: ")
print(student_id)
print(student_name + ' ' + student_id)
add_student(student_name, student_id)
print(student_name + ' ' + student_id)
print(students)
elif user_respond == "No":
break
else:
print("Invalid answer 1")
except KeyError:
print("Invalid answer 2")
print(students)
Already asked this question and I had a very negative response so I'll forewarn you that I am extremely new to Python and programming as a whole so I don't quite understand most terminology but I'll try anyway
I have to insert a method of deleting a customer account from the customers_list, both stored within bank_system
I shall put a code sample of bank_system here.
The customers_list is found at the top and the method to delete accounts is found near the bottom.
from customer import Customer
from admin import Admin
from account import Account
class BankSystem(object):
def __init__(self):
self.customers_list = []
self.admins_list = []
self.load_bank_data()
def load_bank_data(self):
#CUSTOMER LIST
customer_1 = Customer("Adam", "1234", ["14", "Wilcot Street", "Bath", "B5 5RT"])
account_no = 1234
account_1 = Account(5000.00, account_no)
customer_1.open_account(account_1)
self.customers_list.append(customer_1)
customer_2 = Customer("David", "password", ["60", "Holborn Via-duct", "London", "EC1A 2FD"])
account_no+=1
account_2 = Account(3200.00, account_no)
customer_2.open_account(account_2)
self.customers_list.append(customer_2)
customer_3 = Customer("Alice", "MoonLight", ["5", "Cardigan Street", "Birmingham", "B4 7BD"])
account_no+=1
account_3 = Account(18000.00, account_no)
customer_3.open_account(account_3)
self.customers_list.append(customer_3)
customer_4 = Customer("Ali", "150A", ["44", "Churchill Way West", "Basingstoke", "RG21 6YR"])
account_no+=1
account_4 = Account(18000.00, account_no)
customer_4.open_account(account_4)
self.customers_list.append(customer_4)
customer_5 = Customer("Thomas", "15A", ["4", "Churchill West", "Stoke", "ST21 6YR"])
account_no+=1
account_5 = Account(0, account_no)
customer_5.open_account(account_5)
self.customers_list.append(customer_5)
#ADMIN LIST
admin_1 = Admin("Julian", "1441", True, ["12", "London Road", "Birmingham", "B95 7TT"])
self.admins_list.append(admin_1)
admin_2 = Admin("Eva", "2222", False, ["47", "Mars Street", "Newcastle", "NE12 6TZ"])
self.admins_list.append(admin_2)
def customer_login(self, name, password):
#step A.1 CUSTOMER LOGIN
found_customer = self.search_customers_by_name(name)
if found_customer == None:
return("\n The customer you are looking for has not been found!\n")
else:
if (found_customer.check_password(password) == True):
self.run_customer_options(found_customer)
else:
return("You have input an incorrect password")
def admin_login(self, name, password):
#step A.3 ADMIN LOGIN
found_admin = self.search_admin_by_name(name)
if found_admin == None:
return("\n The administrator you are looking for has not been found!\n")
else:
if (found_admin.check_password(password) == True):
self.run_admin_options(found_admin)
else:
return("You have input an incorrect password")
def search_customers_by_name(self, customer_name):
#step A.2 SEARCHING FOR CUSTOMERS
found_customer = None
for a in self.customers_list:
name = a.get_name()
if name == customer_name:
found_customer = a
if found_customer == None:
print("\n The customer %s doesn't exist! Please try again...\n" %customer_name)
else:
return found_customer
def main_menu(self):
#MAIN MENU OPTIONS
print()
print()
print ("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-")
print()
print ("Welcome to the Python Bank System")
print()
print ("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-")
print ("1) Admin login")
print ("2) Customer login")
print ("3) Quit the Python Bank System")
print (" ")
option = int(input("Choose your option: "))
return option
def run_main_option(self):
loop = 1
while loop == 1:
choice = self.main_menu()
if choice == 1:
#ADMIN LOGIN
name = input ("\n Please input admin name: ")
password = input ("\n Please input admin password: ")
msg = self.admin_login(name, password)
print(msg)
elif choice == 2:
#CUSTOMER LOGIN
name = input ("\n Please input customer name: ")
password = input ("\n Please input customer password: ")
msg = self.customer_login(name, password)
print(msg)
elif choice == 3:
loop = 0
print ("Thank you for stopping by the bank!")
def trasnfer_money(self, sender_account, receiver_name, receiver_account_no, amount):
#TRANSFERRING MONEY TO OTHER ACCOUNTS
pass
def customer_menu(self, customer_name):
#CUSTOMER SPECIFIC MENU
print (" ")
print ("Welcome %s : Your transaction options are:" %customer_name)
print ("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-")
print ("1) Transfer money")
print ("2) Other account operations")
print ("3) profile settings")
print ("4) Sign out")
print (" ")
option = int(input ("Choose your option: "))
return option
def run_customer_options(self, customer):
#CUSTOMER OPTIONS
account = customer.get_account()
loop = 1
while loop == 1:
choice = self.customer_menu(customer.get_name())
if choice == 1:
pass
elif choice == 2:
account.run_account_options()
elif choice == 3:
customer.run_profile_options()
elif choice == 4:
loop = 0
print ("Exit account operations")
def search_admin_by_name(self, name):
#step A.4 SEARCHING FOR ADMINS
found_admin = None
admin_name = name
for a in self.admins_list:
name = a.get_name()
if name == admin_name:
found_admin = a
if found_admin == None:
print("\n The administrator %s doesn't exist! Please try again...\n" %admin_name)
else:
return found_admin
def admin_menu(self, admin_name):
#ADMINISTRATOR SPECIFIC MENU
print (" ")
print ("Welcome Admin %s : Available options are:" %admin_name)
print ("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-")
print ("1) Transfer money")
print ("2) Customer account operations")
print ("3) Customer profile settings")
print ("4) Admin profile settings")
print ("5) Delete customer")
print ("6) Print all customers detail")
print ("7) Sign out")
print (" ")
option = int(input ("Choose your option: "))
return option
def run_admin_options(self, admin):
#ADMINISTRATOR OPTIONS
loop = 1
while loop == 1:
choice = self.admin_menu(admin.get_name())
if choice == 1:
pass
elif choice == 2:
#step A.5 SEARCHING FOR CUSTOMERS
customer_name = input("\n Please input customer name :\n")
customer = self.search_customers_by_name(customer_name)
if customer != None:
account = customer.get_account()
if account != None:
account.run_account_options()
elif choice == 3:
#step A.6 UPDATING CUSTOMER NAME
customer_name = input("\n Please input customer name :\n")
customer = self.search_customers_by_name(customer_name)
if customer != None:
customer.run_profile_options()
elif choice == 4:
#step A.7 UPDATING ADMIN NAME (SELF ONLY)
admin.run_profile_options()
elif choice == 5:
#step A.8 DELETING CUSTOMER
if admin.has_full_admin_right() == True:
name = input("\n Please input customer name you want to delete :\n")
customer_account = self.search_customers_by_name(name)
if customer_account !=None:
print ("The customer does not exist")
else: self.customers_list.remove(name)
else:
print("\n Only administrators with full admin rights can remove a customer from the bank system!\n")
elif choice == 6:
#step A.9 PRINTING ALL CUSTOMER DETAILS
self.print_all_accounts_details()
elif choice == 7:
loop = 0
print ("Exit account operations")
def print_all_accounts_details(self):
# list related operation - move to main.py
i = 0
for c in self.customers_list:
i+=1
print('\n %d. ' %i, end = ' ')
c.print_details()
print("------------------------")
app = BankSystem()
app.run_main_option()
With the code I have currently, Python shell returns this:
Please input customer name you want to delete :
Adam
The customer does not exist
Welcome Admin Julian : Available options are:
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
1) Transfer money
2) Customer account operations
3) Customer profile settings
4) Admin profile settings
5) Delete customer
6) Print all customers detail
7) Sign out
Choose your option:
As you can see, when I enter 'Adam' Python simply returns 'The customer does not exist'
Considering this and then looking back through my code and to the method that would delete the account, this would mean that the search_customers_by_name method does not work correctly. However all other options that use this method work perfectly.
What can I do to correct this?
In the deletion option, you are displaying the message that the customer does not exist if there is a customer found (if customer_account != None:). By reversing this (if customer_account == None:) it will alert you if it did not found the customer, which I think is the desired behavior. The corrected code is below:
elif choice == 5:
#step A.8 DELETING CUSTOMER
if admin.has_full_admin_right() == True:
name = input("\n Please input customer name you want to delete :\n")
customer_account = self.search_customers_by_name(name)
if customer_account == None:
print ("The customer does not exist")
else: self.customers_list.remove(name)
else:
print("\n Only administrators with full admin rights can remove a customer from the bank system!\n")