zoukankan      html  css  js  c++  java
  • Python--作业2--对员工信息文件,实现增删改查操作

    函数练习:

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author:Huanglinsheng
    
    
    def calc(x,y):
        res = x**y
        return res
    c = calc(2,4)
    print("计算结果是 %s" %c)
    
    def stu_register1(name,age,country,course):
    #def stu_register2(name,age,course,country="CN"):
        print("------注册学生信息------")
        print("姓名:",name)
        print("年龄:",age)
        print("国籍:",country)
        print("课程:", course)
    
    stu_register1("hc",25,"USA","OPS1")
    stu_register1("hls",24,"China","OPS2")
    stu_register1("hht",20,"Vn","OPS3")
    
    def stu_resgister3(name,age,*args):
        print(name,age,args)
    stu_resgister3("huanglinsheng",22,"CN")
    
    def stu_resgister4(name,age,*args,**kwargs):
        print(name,age,args,kwargs)
    stu_resgister4("hucong",24,"CN","OPS",sex="MAN",province="hubei")
    
    
    '''局部变量'''
    name = "huanglinsheng"
    def change_name(name):
        print("before change:",name)
        name =  "hls"
        print("after change",name)
    change_name(name)
    print("外部的name改变没?",name)
    
    
    '''返回值'''
    '''
    要想获取函数的执行结果,就可以用return语句把结果返回
    注意:
    1. 函数在执行过程中只要遇到return语句,就会停止执行并返回结果,so 也可以理解为 return 语句代表着函数的结束
    2. 如果未在函数中指定return,那这个函数的返回值为None 
    '''
    
    
    '''
    递归
    在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数
    '''
    def calc(n):
        print(n)
        if int(n/2) == 0:
            return n
        return calc(int(n/2))
    calc(10)
    
    
    
    '''递归函数实际应用案例,二分查找'''
    data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]
    
    def binary_search(dataset,find_num):
        print(dataset)
    
        if len(dataset) > 1:
            mid = int(len(dataset)/2)
            if dataset[mid] == find_num:
                print("找到数字",dataset[mid])
            elif dataset[mid] > find_num:
                print("33[31;1m找的数在mid[%s]左面33[0m" %dataset[mid])
                return binary_search(dataset[0:mid],find_num)
            else:
                print("33[32;1m找的数在mid[%s]右面33[0m" % dataset[mid])
                return binary_search(dataset[mid+1:],find_num)
        else:
            if dataset[0] == find_num:
                print("找到数字啦", dataset[0])
            else:
                print("没的分了,要找的数字[%s]不在列表里" % find_num)
    
    binary_search(data,17)
    
    '''
    内置参数详解 https://docs.python.org/3/library/functions.html?highlight=built#ascii 
    '''
    View Code

    需求:

         1.可进行模糊查询,语法至少支持下面3种:

             1.1 select name,age from staff_table where age > 22

             1.2 select  * from staff_table where dept = IT

             1.3 查到的信息,打印后,最后面还要显示查到的条数 

         2.可创建新员工纪录,以phone做唯一键,staff_id需自增

         3.可删除指定员工信息纪录,输入员工id,即可删除

         4.可修改员工信息,语法如下:

            1.UPDATE staff_table SET dept= 无 where dept = IT

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author:Huanglinsheng
    
    import os
    
    # 查询方式一:select * from data_staff.txt where age >= 22
    # 查询方式二:select * from data_staff.txt where dept = "IT"
    # 查询方式三:select * from data_staff.txt where enroll_date like "2013"
    
    def Search():
        data=input("Input your select info:")
        data = data.split(' ')
        con = data[7]
        asp = data[5]
        count = 0
        with open('data_staff.txt','r',encoding='utf-8') as f:
            if asp == 'age':
                for line in f:
                    if int(line.split(',')[2]) >= int(con):
                        print(line)
                        count +=1
            elif asp == 'dept':
                for line in f:
                    if line.split(',')[4] in con:
                        print(line)
                        count +=1
            else:
                for line in f:
                    if line.split(',')[5].split('-')[0] in con:
                        print(line)
                        count +=1
            print('查询结束,共查到符合条件的信息 %d 条' %count)
    
    # 添加语法: name,age,phone,dept,enroll-date
    def Add():
        data = input("请输入要添加员工的信息:")
        list_data = data.strip().split(',')
        list_all = []
        f = open('data_staff.txt','r+')
        for line in f:
            list_all.append(line.strip().split(',')[3])
        if list_data[2] in list_all:
            print("该用户已经存在!!")
        else:
            for line in f:
                f.write(line)
            staff_id = str(len(list_all) + 1)
            list_data.insert(0,str(staff_id))
            f.write('
    ')
            f.write(','.join(list_all))
            f.close()
            print("添加成功")
    
    # 删除语法:delete from staff_table where staff_id = 12
    def Delete():
        staff_id = input("输入您要删除员工的Staff_id:")
        staff_id = staff_id.strip().split(' ')[6]
        f = open('data_staff.txt','r')
        f1 = open('new_data_staff.txt','w')
        for line in f:
            in_list = line.split(',')
            if in_list[0] < staff_id:
                f1.write(line)
            elif in_list[0] > staff_id:
                in_list[0] = str(int(in_list[0]) - 1 )
                f1.write(','.join(in_list))
            else:
                continue
            f.close()
            f1.close()
            os.remove("data_staff.txt")
            os.rename('new_data_staff.txt','data_staff')
            print("删除成功!!")
    
    
    #修改请输入(注意空格和没有引号):UPDATE staff_table SET dept = IT where dept = 运维
    def Change():
        data= input("请输入你要修改的信息:")
        old = data.split(' ')[5]
        new = data.split(' ')[9]
        f = open('data_staff.txt','r',encoding='utf-8')
        f1 = open('new_data_staff','w',encoding='utf-8')
        for line in f:
            if old in line:
                line = line.replace(old,new)
            f1.write(line)
        f.close()
        f1.close()
        os.remove('data_staff')
        os.rename('new_data_staff', 'data_staff')
        print('修改成功')
    
    
    msg_dict = {
        '1':Search,
        '2':Add,
        '3':Delete,
        '4':Change,
        '5':'退出'
     }
    
    while True:
        print("""
        1:查询
        2:添加
        3:删除
        4:修改
        5:退出
        """)
        choice = input("Input your choice:")
        if choice not in msg_dict:
            print("Input error!Pls Input one more time.")
            continue
        if int(choice) == 5:
            exit()
        else:
            msg_dict[choice]()
    View Code

    文本:data_staff.txt

    1,Alex Li,22,13651054684,运维,2013-02-04
    2,Jack Wang,20,13312331232,HR,2014-06-03
    3,Mike Cao,20,15504231232,Sales,2013-05-06
    4,Jack Chen,34,12404231232,HR,2011-02-01
    5,Lu Haojie,21,15204231232,运维,2013-08-12
    View Code
  • 相关阅读:
    【Android】Handler的应用(二):从服务器端加载JSON数据的优化
    [置顶] IOS 开发之 CocoaPods讲解
    POJ 1068 (13.10.11)
    android使用百度地图、定位SDK实现地图和定位功能!(最新、可用+吐槽)
    C++笔记(1)
    WCF讲解
    php5 图片验证码一例
    PHP5 GD库生成图形验证码(汉字)
    mysql中limit的用法实例解析
    Limit参数优化MySQL查询的方法
  • 原文地址:https://www.cnblogs.com/huanglinsheng/p/9372830.html
Copyright © 2011-2022 走看看