Python小练习——创建简单地址簿

  闲来无事,刚花了点时间学完《A Byte Of Python》,写写最后面给的习题:

  创建一个地址簿,写了个简单的文字菜单,根据选择可添加/删除/查找/更改联系人、电话以及邮箱,当然可以扩展为更多信息和操作;程序只是把内容简单打印出来,可以把打印部分变为文件存储。

  写完发现好像当C来使了。菜鸟学习而已,大家勿笑:)

代码
#!/usr/bin/python
#
Filename: practice.py

import sys

class PersonInfomation:
def __init__(self, name, tel, email):
self.name
= name
self.tel
= tel
self.email
= email

def getName(self):
return self.name

def getTel(self):
return self.tel

def getEmail(self):
return self.email

def input(message):
'''input something with the message'''
try:
content
= raw_input(message)
except EOFError:
print 'you put an EOF!'
sys.exit()
except:
print 'unknow error or exception occurred!'
sys.exit()

return content

def addPerson(addressBook):
'''add person information'''
name
= input('Please input person name:')
tel
= input('Please input the tel:')
email
= input('Please input the email:')

infomation
= PersonInfomation(name, tel, email)
addressBook[infomation.getName()]
= [infomation.getTel(), infomation.getEmail()]

print '======== ADD SUCCESS! ========'

def delPerson(addressBook):
'''del person information'''
name
= input('input the person name you want to delete:')
if addressBook.has_key(name):
del addressBook[name]
print '======== DELETE SUCCESS! ========'
else:
print '%s not exist.' % name

def findPerson(addressBook):
'''find the person and print the information'''
name
= input('input the name you want to find:')
if addressBook.has_key(name):
print 'RESULT~~~~~~~~~~~~~~'
print '--->name: %s' % name
print '--->tel: %s' % addressBook[name][0]
print '--->email: %s\n' % addressBook[name][1]
else:
print '--->%s not exist.' % name

def changeInfo(addressBook):
name
= input('input the name you want to change information:')
tel
= input('Please input the tel:')
email
= input('Please input the email:')
addressBook[name]
= [tel, email]
print '======= CHANGE SUCCESS! ========'

def printInfoAndExit(addressBook):
for key, value in addressBook.items():
print '==== PRINT INFOMATION ===='
print 'Name : %s' % key
print 'Tel : %s' % value[0]
print 'Email: %s' % value[1]

sys.exit()

if __name__ == '__main__':
addressBook
= {}
dictHandle
= \
{
'1' : addPerson,
'2' : delPerson,
'3' : findPerson,
'4' : changeInfo,
'5' : printInfoAndExit
}
idleMessage
= '''\
======== M e n u ===========
| AddressBook:        |
| 1. Add person        |
| 2. Del person        |
| 3. Find person          |
| 4. Change infomation        |
| 5. Exit           |
=========================
'''

while True:
print idleMessage
chosen
= raw_input('Select: ')
dictHandle[chosen](addressBook)

 

END

posted @ 2010-07-17 01:02  Linjian  阅读(681)  评论(0)    收藏  举报