python 案例一(电话铺)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 案例一(电话铺)相关的知识,希望对你有一定的参考价值。

经过自己努力,做了一个简单的电话铺的录入和查询小程序,比较简单,喜欢的朋友可以练练手。

题目:

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

用到的知识点:

  1. cPickle
  2. 简单文件读写

代码:

# coding=utf-8
‘‘‘姓名年龄email查询修改‘‘‘

import cPickle as p
import os


class person(object):
    ‘‘‘人员详情‘‘‘
    def __init__(self, name=None, age=None, email=None):
        self.name = name
        self.age = age
        self.email = email

def show_all():
    ‘‘‘打印所有人员‘‘‘
    persons = get_persons()
    if len(persons) > 0:
        for item in persons:
            print name: %s, age: %s, email: %s % (item.name, item.age, item.email)
    else:
        print "There is no person"

def add_person(name, age, email):
    ‘‘‘添加人员‘‘‘
    #判断是否为空
    list = get_persons()
    with file(persons,w) as f:
        list.append(person(name, age, email))
        p.dump(list,f)

def get_persons():
    ‘‘‘获取人员列表‘‘‘
    if not os.path.exists(persons):
        file(persons,w).close()
        return []
    with file(persons) as f:
        data = p.load(f)
        return data if data != None else []

def find_person(name):
    ‘‘‘根据姓名打印信息‘‘‘
    persons = get_persons()
    for person in persons:
        if person.name == name:
            print name: %s, age:%s, email:%s % (person.name,person.age,person.email)
            return
    print This no person named: name

def del_person(name):
    ‘‘‘根据姓名删除人员‘‘‘
    persons = get_persons()
    for person in persons:
        if person.name == name:
            persons.remove(person)
            with file(persons,w) as f:
                p.dump(persons,f)
            print delete success!
            return
    print This no person named: name

def main():
    ‘‘‘显示欢迎语句‘‘‘
    hello = ‘‘‘Welcome please input your purpose 
    1 --> see all persons detail
    2 --> find person by name
    3 --> add person
    4 --> delete person
    5 --> exit ‘‘‘
    while True:
        m = raw_input(hello + \n->)
        #print m
        if m == 3:
            name = raw_input("name: ")
            age = raw_input("age:")
            email = raw_input("email:")
            add_person(name, age, email)
            print "ok!"
        elif m == 1:
            show_all()
        elif m == 2:
            name = raw_input("Enter the person‘s name: ")
            find_person(name)
        elif m == 4:
            name = raw_input("Enter the person‘s name: ")
            del_person(name)
        elif m == 5:
            os.sys.exit(0)
if __name__ == __main__:
    main()

 

以上是关于python 案例一(电话铺)的主要内容,如果未能解决你的问题,请参考以下文章

项目练习--自制电话铺功能

android小知识点代码片段

android案例一 电话拨号器

女友半夜加班发自拍Python男友用30行代码发现秘密

女友半夜加班发自拍Python男友用30行代码发现秘密

十个html5代码片段,超实用,一定要收藏