A Bite of Python在文章的结尾要求写一个Python地址簿程序。俗话说:光说不练假把式。于是,就写了一个。
# Filename : addressBook.py#At first, we abstract the model.import osimport cPickleclass Person: def __init__(self,name,email = "",mobile = "",teleNumber = ""):self.name = nameself.email = emailself.mobile = mobileself.teleNumber = teleNumberaddressPath = 'addressBook.data'addressBook = {}if os.path.exists(addressPath):addressFile = file(addressPath)addressBook = cPickle.load(addressFile)isQuit = Falseprint '''Input a command.'A' or 'a' Add a person'D' or 'd' Delete a person'F' or 'f' Find a peron'M' or 'm' Modify a person'Q' or 'q' Quit'''while not isQuit:command = raw_input("/nInput a command:")if(command == 'A' or command == 'a'):print 'Input Person informaton: name email mobile teleNumber'info = raw_input("Person Info:")info = info.split(' ')person = Person(info[0],info[1],info[2],info[3])if not addressBook.has_key(person.name):addressBook[person.name] = personprint "Success"else:print "In AddressBook, there is a same name with",person.name,"."elif(command == 'D' or command == 'd'):print "Input the peroson's name"name = raw_input("Name:")if addressBook.has_key(name):del addressBook[name]print "Success"else:print "No Person is called",nameelif(command == 'F' or command == 'f'):print "Input the name of the person which you want find"name = raw_input('Name:')if not addressBook.has_key(name):print "No Person is called",nameelse:print 'Email:',addressBook[name].emailprint 'Mobile:',addressBook[name].mobileprint 'TeleNumber:',addressBook[name].teleNumberelif(command == 'M' or command == 'm'):print "Input the person's Name"name = raw_input("Name:")if addressBook.has_key(name):if raw_input("Modify email? y/n/n") == 'y':addressBook[name].email = raw_input("Input Email:")if raw_input("Modify mobile? y/n/n") == 'y':addressBook[name].mobile = raw_input("Input mobile:")if raw_input("Modify teleNumber? y/n/n") == 'y':addressBook[name].teleNumber = raw_input("Input teleNumber:")print "Success"else:print "No Person is called",nameelif(command == 'Q' or command == 'q'):print 'The program is exit'isQuit = Trueelif(command == 'L' or command == 'l'):print '****************************************'for name,detail in addressBook.items():print 'Name:',detail.nameprint 'Email:',detail.emailprint 'Mobile:',detail.mobileprint 'TeleNumber:',detail.teleNumberprintprint '****************************************'else:print command,"is not a command"#Write to the filetry:addressFile = file(addressPath,'w')cPickle.dump(addressBook,addressFile)finally:addressFile.close()
初学乍练,见谅见谅。