In: Computer Science
Write in Python.
come up with a programming task for which you will write your own program. It should be a purposeful and non-trivial program, bigger than any programming assignment. But it should not be something too ambitious that you may not end up finishing by the deadline. The program must not be something available on the Internet or in a book. The program must satisfy the following five requirements:
Please feel free to contact the instructor if any help is needed at any stage of the project.
Submission:
#class phonebook, that will read phonebook from a file, and load
it to a dictionary
class PhoneBook:
#class constructor
def __init__(self):
try:
#reading from the file
f = open('phonebook.txt', 'r')
data = f.readlines()
pb = {}
#populating dictionary
for line in data:
line = line.split(',')
pb.update({line[0].strip(): line[1].strip()})
self.phonebook = pb
f.close()
except FileNotFoundError:
self.phonebook = {}
#function to get phone number by name
def getPhoneNumber(self, name):
if name in self.phonebook.keys():
return self.phonebook[name]
else:
return "Name not in Phone book"
#function to get name by phone number
def getName(self, phone_number):
for name, number in self.phonebook.items():
if number == phone_number:
return name
return "Number not in phonebook"
#function to add a new contact in the phonebook
def addContact(self, name, number):
self.phonebook.update({name: number})
f = open('phonebook.txt', 'w')
for name, number in self.phonebook.items():
f.write(name +", " + number + "\n")
f.close()
return "Contact Added Successfully"
#function to display menu to user and return the choice entered
by user
def menu():
print("1. Get Phone number by name.")
print("2. Get name by phone number.")
print("3. Add a new contact in phonebook.")
print("0. Exit")
ch = int(input("Enter your choice: "))
return ch
#function to perform operation based on user choice
def operation(pb, ch):
if ch == 1:
name = input("Enter Name: ")
print(name, ':', pb.getPhoneNumber(name))
elif ch == 2:
number = input("Enter Phone number: ")
print(number, ':', pb.getName(number))
elif ch == 3:
name = input("Enter Name: ")
number = input("Enter Phone number: ")
pb.addContact(name, number)
#main function
def main():
#create object of phonebook class
pb = PhoneBook()
ch = menu()
while ch != 0:
operation(pb, ch)
print("")
ch = menu()
main()
phonebook.txt
Shashank Shukla,
123456789
Abhiram, 456789123
Dale, 45685217
Nathan, 78954213
george, 4861265
Sarah, 45645123
Carrie, 786523
Aria, 777777777