Python程序出炉了

本文介绍了一个简单的Python地址簿程序实现,该程序使用类定义来存储联系人信息,并提供了添加和检索联系人的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


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


#! /usr/bin/python
#Filename: address-book.py
#Author: gogdizzy

import sys
import os
import pickle

class PersonInfo:
	def __init__( self, name, age, tel, email ):
		self.name = name
		self.age = age
		self.tel = tel
		self.email = email
	def 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] = info
	def 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_file
	fd = open( db_file, "rb" )
	try:
		ab = pickle.load( fd )
	except:
		sys.exit( 'File format error' )
	finally:
		print 'close', db_file
		fd.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 ):
					break
			while True:
				try:
					age = int( input( '\nplease input age(integer): ' ) )
					if( age < 0 ):
						raise Exception()
				except:
					print 'Please input a positive integer'
					continue
				else:
					break
			tel = raw_input( '\nplease input tel: ' )
			email = raw_input( '\nplease input email: ' )
			ab.put( name, PersonInfo(name, age, tel, email) )
		elif( cmd == 'q' ):
			break
finally:
	pickle.dump( ab, fd )
	fd.close()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值