Python程序出炉了

来源:互联网 发布:淘宝怎么设置自动回复 编辑:程序博客网 时间:2024/05/22 03:42

最近学习Python,看了入门书《A Byte Of Python》,这本书很薄,例子很多,非常适合自学。虽然不能深入理解,但是对于我这种随便用用的已经足够了。在最后,作者出了一个问题,让大家写一个地址簿。我简单的实现了一个,发现真的不难。


当然能写出这么“大”的程序,也归功于我之前一直按照书里的代码写了许多小程序。


#! /usr/bin/python#Filename: address-book.py#Author: gogdizzyimport sysimport osimport pickleclass PersonInfo:def __init__( self, name, age, tel, email ):self.name = nameself.age = ageself.tel = telself.email = emaildef display( self ):print 'Name: {0}\nAge: {1}\nTel: {2}\nEmail: {3}'.format( self.name, self.age, self.tel, self.email )class AddrBook:def __init__( self ):self.dict = {}def put( self, name, info ):self.dict[name] = infodef get( self, name ):if( self.dict.has_key( name ) ):self.dict[name].display()else:print name, 'is not in address book'if ( len( sys.argv ) != 2 ):sys.exit( 'Usage: {0} datafile'.format( sys.argv[0] ) )db_file = sys.argv[1]ab = AddrBook()if ( os.path.isfile( db_file ) ):print 'Load data from', db_filefd = open( db_file, "rb" )try:ab = pickle.load( fd )except:sys.exit( 'File format error' )finally:print 'close', db_filefd.close()else:print db_file, 'is not exist, create it'fd = open( db_file, 'wb' )try:while True:cmd = raw_input( '\nPlease input cmd( \'p\'ut \'g\'et \'q\'uit ): ' )if ( cmd == 'g' ):ab.get( raw_input( '\nplease input name: ' ) )elif( cmd == 'p' ):while True:name = raw_input( '\nplease input name: ' )if( len(name) > 0 ):breakwhile True:try:age = int( input( '\nplease input age(integer): ' ) )if( age < 0 ):raise Exception()except:print 'Please input a positive integer'continueelse:breaktel = raw_input( '\nplease input tel: ' )email = raw_input( '\nplease input email: ' )ab.put( name, PersonInfo(name, age, tel, email) )elif( cmd == 'q' ):breakfinally:pickle.dump( ab, fd )fd.close()


原创粉丝点击