Python地址簿程序V1.0

Iris posted @ 2011年5月16日 10:38 in Python学习 with tags python addressbook , 1965 阅读

先解决这样一个问题:创建你自己的命令行地址簿 程序。 在这个程序中,可以添加、修改、删除和搜索你的联系人(朋友、家人和同事等等) 以及它们的信息(诸如电子邮件地址和/或电话号码)。这些详细信息应该被保存下来 以便以后提取。

思路: 创建一个类来表示一个人的信息。使用字典储存每个人的对象,把他们的名字作为键。 使用cPickle模块永久地把这些对象储存在你的硬盘上。使用字典内建的方法添加、 删除和修改人员信息。

一旦你完成了这个程序,你就可以说是一个Python程序员了。

import sys
import cPickle

class Person:
    def __init__(self):
        self.name = ''
        self.info = ''
        self.dict ={self.name: self.info}

    def add(self):
        self.name = raw_input('Enter name:')
        if self.name in self.dict.keys():
            print 'The name already exists!'
        else:
            self.info = raw_input('Enter info:')
            self.dict[self.name] = self.info
            cPickle.dump(self.dict,open('./info.txt','w'))
            print 'Contact saved!'
        
        
    def modify(self):
        self.name = raw_input('Enter name:')
        if self.name in self.dict.keys():
            self.info = raw_input('Enter new info:')
            self.dict[self.name] = self.info
            cPickle.dump(self.dict,open('./info.txt','w'))
            print 'Contact modified!'
        else:
            print 'The name not exist!'
            
    def search(self):
        self.name = raw_input('Enter name:')
        if self.name in self.dict.keys():
            print 'Name:%s, Info:%s' % (self.name, self.info)
        else:
            print 'The name not exist!'

    def delete(self):
        self.name = raw_input('Enter name:')
        if self.name in self.dict.keys():
            del self.dict[self.name]
            print 'Delete Success!'
        else:
            print 'The name not exist!'
    

if __name__ =='__main__':
    p1 = Person()
    while True:
        str = raw_input('What are you going to do(add/modify/search/delete/quit)?')

        if str == 'add':
            p1.add()
        elif str == 'modify':
            p1.modify()
        elif str == 'search':
            p1.search()
        elif str == 'delete':
            p1.delete()
        else:
            print 'No more instructions. Quit sys!'
            break

 


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

Copyright © 2007

Webdesign, tvorba www stránek

Valid XHTML 1.1