Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class phonebook():
- def __init__(self):
- self.phonedic = {} #creates an empty dictionary
- self.alias = {}
- def add(self, name, number): #this function adds a contact
- d = self.phonedic
- for key, value in d.items():
- if number in value:
- print "That number already exist in the phonebook"
- return
- self.phonedic[name] = number
- self.alias[name] = name
- print name , "has been added."
- def lookup(self, name): #this function can look up a contact
- print "self.phonedic.has_key = " , self.phonedic[name]
- print "self.alias.has_key= ", self.alias[name]
- if self.phonedic.has_key(name):
- print name + ":s" , "number:" , self.phonedic[name]
- elif self.alias.has_key(name):
- print name + ":s" , "number:" , self.alias[name]
- else:
- print name , "does not exist."
- def alias1(self, name, nickname): #creates an alias for the contact, so it can be found under both names
- print "namn" , name , "nickname:", nickname
- if self.phonedic.has_key(name):
- self.alias[nickname] = name
- print "alias tillagd"
- print self.alias
- else:
- print "Can't create an alias for a non-existent contact."
- def change(self, name, number): #changes the number of a contact
- if self.phonedic.has_key(name):
- self.phonedic[name] = number
- print "The new number is saved."
- else:
- print "Couldnt find the contact", name
- def save(self, filename): #saves the phonebook to a file
- f = open("C://Python27//Labbar//" + filename, "w")
- for key, value in self.phonedic.items():
- k = value + ";" + key + ";" + "\n"
- f.write(str(k))
- f.close()
- print "File saved with the name: " , filename
- def load(self, filename):
- f = open("C://Python27//Labbar//" + filename, "r")
- for line in f:
- x = line.split(";")
- x[-1] = x[-1].strip("\n")
- number = x[0]
- name = x[1]
- self.phonedic[name] = number
- f.close()
- def main():
- pb = phonebook()
- while True:
- prompt = raw_input("Phonebook>>")
- x = prompt.split()
- try:
- function = x[0]
- if function == "add":
- pb.add(x[1],x[2])
- elif function == "lookup":
- pb.lookup(x[1])
- elif function == "save":
- pb.save(x[1])
- elif function == "alias1":
- pb.alias1(x[1],x[2])
- elif function == "change":
- pb.change(x[1],x[2])
- elif function == "quit":
- break
- elif function == "load":
- pb.load(x[1])
- else:
- print "Non-existent function, try again."
- except: IndexError
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement