標籤:style blog http os io for 2014 ar
看了一些基礎的 Python 新手教程後,深深感覺到 Python 的簡潔與強大,這是我的第一個 Python Demo。下面是完整代碼與執行。代碼:
# encoding: utf-8‘‘‘@author: Techzero@email: [email protected]@time: 2014-4-30 下午1:31:04‘‘‘import osimport sysimport cPickle as pclass Person: def __init__(self, name, email): ‘‘‘Initializes the person‘s data.‘‘‘ self.name = name self.email = emaildef create(): """Create new person and input email""" global Persons try: name = raw_input("Please input name:") while Persons.has_key(name): name = raw_input("This name has already exist, please input new name:") email = raw_input("Please input Email:") except EOFError: print ‘\nEOF Error‘ sys.exit() Persons[name] = email print ""def delete(): """Search person by name and delete""" global Persons try: name = raw_input("Please input the person‘s name you want to delete:") except EOFError: print ‘\nEOF Error‘ sys.exit() if Persons.has_key(name): del Persons[name] save() else: print "No one called",name,"!\n"def modify(): """Search person by name and modify email""" global Persons try: name = raw_input("Please input the person‘s name you want to modify:") if Persons.has_key(name): del Persons[name] email = raw_input("Please input new email:") Persons[name] = email save() else: print "No one called",name,"!\n" except EOFError: print ‘\nEOF Error‘ sys.exit()def save(): """Save Persons to file""" global Persons File = ‘person.dat‘ f = file(File, ‘w‘) p.dump(Persons, f) f.close() print "Operation Done!\n"def read(): """Read person from file""" global Persons File = ‘person.dat‘ if os.path.exists(File): f = file(File) Persons = p.load(f) f.close() else: File = ‘person.dat‘ f = file(File, ‘w‘) f.close()def display(): """Display all persons in the dictionary""" global Persons for name, email in Persons.items(): print " ",name,email print ""def search(): """Search person by name""" global Persons try: name = raw_input("Please input the person‘s name you want to search:") except EOFError: print ‘\nEOF Error‘ sys.exit() if Persons.has_key(name): print " ",name,Persons[name],"\n" else: print "No one called",name,"!\n"def menu(): """Display a menu to choose operation""" choose = "0" while True: #i = os.system("cls") print‘‘‘1----Create2----Delete3----Modify4----Search5----Display6----Exit‘‘‘ try: choose = raw_input("Please choose an item(1-6):") except EOFError: print ‘\nEOF Error‘ sys.exit() if choose == "1": create() elif choose == "2": delete() elif choose == "3": modify() elif choose == "4": search() elif choose == "5": display() elif choose == "6": print "Thanks for using!" sys.exit() else: print ""Persons = {}read()menu()
執行
本文固定連結:http://www.itechzero.com/coding/python/python-development-with-eclipse-pydev-install-tutorial/,轉載請註明出處。