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()
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)
Trying to run a basic search program with Python (beginner level). All other options work (N, Q) but when trying to select S, I receive a nameerror for "plateNum" as not being defined. Even when entering new information, then trying to recall it, it won't allow me to search for the already inputted information.
#mainMenu Function
def displayMainMenu():
print("\nMAIN MENU")
print("(S) Search vehicle by license plate")
print("(N) Add new vehicle")
print("(Q) Quit")
def searchPlate(plateNum, choice):
plateNum = input("Enter 7-DIGIT license plate number: ")
try:
file = open(plateNum + " data.txt", "r")
DataList = file.readlines()
file.close()
except FileNotFoundError:
print("\nContact not found!\n")
else:
print("(P)late Number")
print("(Ma)ke")
print("(Mo)del")
print("(Y)ear")
print("(C)olor")
print("(I)All information")
choice = input(">> ").upper()
print("\n" + plateNum)
if choice == "Ma":
print(DataList[0])
if choice == "Mo":
print(DataList[1])
if choice == "Y":
print(DataList[2])
if choice == "C":
print(DataList[3])
if choice == "I":
print(DataList[0])
print(DataList[1])
print(DataList[2])
print(DataList[3])
#AddVehicle function
def newVehicle():
newPlate = input("Enter license plate of vehicle: ")
newMake = input("Enter Make of vehicle: ")
newModel = input("Enter model of vehicle: ")
newYear = input("Enter year of vehicle: ")
newColor = input("Enter color(s) of vehicle: ")
newList = [newPlate + "\n", newMake + "\n", newModel + "\n", newYear + "\n", newColor + "\n"]
file = open(newPlate + " data.txt", "w")
file.writelines(newList)
file.close()
print("Vehicle Successfully Saved")
#choice
choice = ""
while choice != "Q":
displayMainMenu()
choice = input(">> ").upper()
if choice == "S":
searchPlate(plateNum,choice)
if choice == "N":
newVehicle()
else:
print("Have a nice day!")
while choice != "Q":
displayMainMenu()
choice = input(">> ").upper()
if choice == "S":
searchPlate(plateNum,choice)
platenum isn't defined there in the global scope, that's why you're getting the error. Just change it to
plateNum = ""
while choice != "Q":
displayMainMenu()
choice = input(">> ").upper()
if choice == "S":
searchPlate(plateNum,choice)
or, remove plateNum from the arguments.
You defined searchPlate to take a plate number as an argument, but then you
try to use an undefined variable of the same name to provide that argument, and
you immediately replace whatever value might be passed with a new input.
You do the same thing with choice; that name is at least defined when you call searchPlate, but you don't need to pass its value to the function.
Replace the definition of searchPlate with
def searchPlate(plateNum):
try:
file = open(plateNum + " data.txt", "r")
DataList = file.readlines()
file.close()
except FileNotFoundError:
print("\nContact not found!\n")
else:
...
then replace its use with something like
if choice == "S":
x = input("Enter 7-DIGIT license plate number: ")
searchPlate(x)
I'm trying to make a simple library where the user can add and remove books from his shopping cart, but I don't know how to use if statements with OOP and classes.
try:
class library:
def __init__(self, books, customer):
self.books = books
self.customer = customer
# sign:
check = input("manager account(1), customer account(2): ")
if check == "2":
#age >= 18
age = int(input("enter your age: "))
if age >= 18:
#name
name = input("enter your firstname: ")
# ID
import random
x = "ID"+str(random.randint(101,999))
print(f"your ID is: {x}")
print("you should memorize it")
y = input("enter password that has at list 8 caracterse: ")
# Password
while len(y) < 8:
y = input("enter password that has at list 8 caracterse: ")
print(f"your password is: {y}")
print("you should memorize it")
data = [x,y]
choice_1 = input("check your shopping cart(1): \nadd books to your shopping cart(2): \nremove books from your shopping cart(3): ")
if choice_1 == "1":
def __str__(self):
return f"customer {self.customer} bought those books{self.books}"
elif choice_1 == "2":
def __iadd__(self, other):
self.books.append(other)
return self
order = library(["the golsen company"],"Mr.asad")
print(order.books)
order += input("enter a book: ")
print(order.books)
except ValueError as ages:
print(ages)
I don't know if this is the right way to use the if statement with classes so if you can just give me an example to show how it's done correctly?
OK, I have rewritten your code to implement it in a more organized way. Your class "library" was not really a library at all; it is a class for "orders", and I have renamed it as such. I didn't know what you wanted for the manager account, so the manager account just assigns a fake user name without requiring a signup. I also fixed the spelling errors and the tabbing.
import random
import sys
class Order:
def __init__(self, books, customer):
self.books = books
self.customer = customer
def __iadd__(self, other):
self.books.append(other)
return self
def __isub__(self, other):
self.books.remove(other)
return self
def __str__(self):
return f"custumer {self.customer} bought those books {self.books}"
# sign in.
check = input("manager account(1),custumer account(2): ")
if check == '1':
x = 'manager'
if check == "2":
#age >= 18
age = int(input("enter your age: "))
if age < 18:
print("Sorry, you must be at least 18.")
sys.exit(0)
#name
name = input("enter your firstname: ")
# ID
x = "ID"+str(random.randint(101,999))
print(f"your ID is: {x}")
print("you should memorize it")
# Password
y = input("enter password that has at least 8 characters: ")
while len(y) < 8:
y = input("enter password that has at least 8 characters: ")
print(f"your password is: {y}")
print("you should memorize it")
# Main menu.
order = Order( [], x )
while True:
print('---')
choice_1 = input("1. check your shopping cart\n2. add books to your shopping cart\n3. remove books from your shopping cart\n4. quit: ")
if choice_1 == "1":
print( order )
elif choice_1 == "2":
order += input("enter a book: ")
elif choice_1 == "3":
book = input("enter a book: ")
if book in order.books:
order -= book
else:
print( f"{book} is not in your cart." )
elif choice_1 == "4":
break
when you said "fonction", I think you mean "function". When you make a try: block, you must also add an except: block. Also, don't put code directly in the class. Put it inside a function (a.k.a methods). I put the code starting from # sign in the __int__ method. We generally don't put methods (functions) inside other methods. So, put the __str__ and __iadd__ methods outside the __init__ method. To call it, use self.__str__() and self.__iadd__().
Here is the updated code:
try:
class library:
def __init__(self, books, customer):
self.books = books
self.customer = customer
# sign:
check = input("manager account(1), customer account(2): ")
if check == "2":
# age >= 18
age = int(input("enter your age: "))
if age >= 18:
# name
name = input("enter your firstname: ")
# ID
import random
x = "ID" + str(random.randint(101, 999))
print(f"your ID is: {x}")
print("you should memorize it")
y = input("enter password that has at list 8 caracterse: ")
# Password
while len(y) < 8:
y = input("enter password that has at list 8 caracterse: ")
print(f"your password is: {y}")
print("you should memorize it")
data = [x, y]
choice_1 = input("check your shopping cart(1): \nadd books to your shopping cart(2): ")
if choice_1 == "1":
self.__str__()
elif choice_1 == "2":
self.__iadd__()
# age < 18
elif age < 18:
print("this library is not for your age")
def __iadd__(self, other):
self.books.append(other)
return self
def __str__(self):
return f"customer {self.customer} bought those books{self.books}"
except:
pass
order = library(["the golsen company"], "Mr.asad")
print(order.books)
order += input("enter a book: ")
print(order.books)
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()
If I create a dictionary that I need to access in multiple functions what would be the best way to pass it?
What I currently am doing keeps reseting the dictionary to empty. If I print in the addDictionary() I get the result I want. However, when I go to look up a element using the key in lookUpEntry(), I can't find it. When I print I get an empty dictionary. I also have to eventually pickle and unpickle so if anyone has any feedback on that, that would also help.
import pickle
def dictionary():
addressBook = {}
return addressBook
def addPerson():
personLastName = input("Enter the last name of "
"the person you want to add: ").lower()
personFirstName = input("Please enter the first name of "
"the person you want to add: ")
localPart = input("Please enter the local part of the email address")
while not localPart.isalnum():
localPart = input("Please enter a valid input, a-z and numbers 0-9: ")
domain = input("Please enter the domain of the email addres: ")
while not domain.isalnum():
domain = input("Please enter a valid input, a-z and numbers 0-9: ")
topLevelDomain = input("Please enter the top level domain, examples: com, net, org: ")
while not topLevelDomain.isalnum() or len(topLevelDomain) > 3:
topLevelDomain = input("Please enter only letters, a-z and not more then 3 characters: ")
personEmail = localPart + "#" + domain + "." + topLevelDomain
personStreetAddress = input("Please enter house number and street of the person you want to add: ")
personCityState = input("Please enter the city, state abbreviation and zipcode of the person you want to add: ")
personPhone = input("Please enter the phone number of the person you want to add: ")
personPhoneStr = personPhone.strip("-")
while not personPhoneStr.isdigit() and not len(personPhoneStr) == 10:
personPhone = input("Error. That is not a valid phone number. Try again: ")
personPhoneStr = personPhone.strip("-")
return personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone
def addDictionary():
addressBook = dictionary()
personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone = addPerson()
addressBook[personLastName] = personFirstName, personEmail, personStreetAddress, personCityState, personPhone
print(personFirstName,personLastName, "has been added to the address book!")
print(addressBook)
return addressBook
def lookUpEntry():
addressBook = dictionary()
keyName = input("Enter the last name of the person you are trying to find.")
while not keyName in addressBook:
keyName = input("That name is not in the address book. Please try again.").lower()
x = input("Enter '1' if you want to look up a email. Enter '2' if you want to look "
"up a persons address. Enter '3' to look up a persons phone number: ")
if x == "1":
print("The email of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[1]])
elif x == "2":
print("The address of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[2]], addressBook[keyName[3]])
elif x == "3":
print("The phone number of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[4]])
else:
print("Sorry that item is not stored in this address book.")
def main():
addDictionary()
lookUpEntry()
main()
Currently you define dictionary as
def dictionary():
addressBook = {}
return addressBook
Here you create a new dictionary every time it is called. Try replacing this with
# a global dictionary
_addressBook = {}
def dictionary():
return _addressBook