码迷,mamicode.com
首页 > 其他好文 > 详细

函数作业

时间:2017-10-30 17:02:42      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:upd   exist   冻结   split()   set   money   hang   string   一键   

一、模拟sql查询

员工信息表程序,实现增删改查操作

作业要求:

1.可进行模糊查询,语法至少支持下面3种:
  select name,age from staff_table where age > 22
  select * from staff_table where dept = ""IT""
select * from staff_table where enroll_date like ""2013""

2.查到的信息,打印后,最后面还要显示查到的条数
3.可创建新员工纪录,以phone做唯一键,staff_id需自增
4.可删除指定员工信息纪录,输入员工id,即可删除
5.可修改员工信息,语法如下:
  UPDATE staff_table SET dept="Market" WHERE where dept = "IT"

*员工信息表的数据要存在文件里, 不是数据库,数据库还没学呢,上面的select, update,看上去像sql的语句也只是让你模拟,sql语句我们也没学, 只是让你写成这种查询格式 。

技术分享
# -*- coding:utf-8 -*-

import os

def select(sql):
    """
    查询:
    查询语法一:select name,age from staff_table where age > 22
    查询语法二:select * from staff_table where dept = IT
    查询语法三:select  * from staff_table where enroll_date like "2013"
    """
    if len(sql) == 0 or select not in sql.lower():
       print ("\033[31;1m输入为空或语句有问题,请输入正确的SQL语句!\033[0m")
       return
    elif sql.lower().replace( ,‘‘) == "selectname,agefromstaff_tablewhereage>%s"%(sql.lower().split()[-1].strip()):
        with open(staff_table.txt, encoding="utf-8") as f:
            list = []
            print ("-"*20)
            for line in f:
                i = line.strip().split(",")
                #判断数据库中数据的格式是否正确
                if len(i) !=6:
                    continue
                field1 = i[1]
                field2 = i[2]
                field = [field1, field2]
                if field2 > sql.split()[-1]:
                    list.append(field)
            for i in list:
                print(\t | \t.join(i))
            print ("-"*20)
            print("共查询到%s条符合条件的信息" %len(list))
            return
    elif sql.lower().replace( ,‘‘) == "select*fromstaff_tablewheredept=%s"%(sql.lower().split()[-1].strip()):
        with open(staff_table.txt, encoding="utf-8") as f2:
            rows = []
            for line in f2:
                i = line.strip().split(",")
                if len(i) !=6:
                    continue
                if sql.split()[-1]==i[4]:
                    rows.append(i)
            print("-"*100)
            for i in rows:
                print(\t | \t.join(i))
            print("-"*100)
            print("共查询到%s条符合条件的信息" %len(rows))
            return
    elif sql.lower().replace( ,‘‘) == "select*fromstaff_tablewhereenroll_datelike%s"%(sql.lower().split()[-1].strip()):
        with open(staff_table.txt, encoding="utf-8") as f3:
            rows = []
            for line in f3:
                i = line.strip().split(",")
                if len(i) !=6: 
                    continue
                if sql.split()[-1].strip(") == i[5][:4]:
                    rows.append(i)
            print("-"*100)
            for i in rows:
                print(\t | \t.join(i))
            print("-"*100)
            print("查询到%s条符合条件的信息" %len(rows))
            return
    else:
        print("\033[31;1mSQL 语法有误!\033[0m")
        return


def insert(sql):
    """
    添加
    insert into staff_table values (zhangsan,23,138888888888,IT,2017-06-18)
    """
    if len(sql) != 0 and ( in sql and , in sql and ) in sql:
        #获取sql中的插入字段然后放到列表中去
        sql1 = sql.replace(), ‘‘)
        sql2 = sql1[sql.index(() + 1:]
        field_list = sql2.split(,)
    else:
        print ("\033[31;1m输入为空或SQL语句有问题,请输入正确的SQL语句!\033[0m")
        return

    #去每个字段的空格
    if len(field_list) == 5:
        sql_list=[]
        fields=[]
        for f in field_list:
            fields.append(f.lower().strip())
            sql_list.append(f.strip())
    else:
        print ("\033[31;1mSQL语句有问题,请输入正确的SQL语句!\033[0m")
        return

    if sql.lower().replace( ,‘‘) == "insertintostaff_tablevalues(%s,%s,%s,%s,%s)"%tuple(fields):
        if len(sql_list) == 5 and sql_list[2] != ‘‘: #phone 字段不能少,因为是主键
            with open(staff_table.txt, encoding="utf-8")as f:
                phone_list = []
                for line in f:
                    line_list = line.strip().split(",")
                    #过滤掉符合表结构格式的行
                    if len(line_list) !=6:
                        continue
                    phone_list.append(line_list[3])
                if sql_list[2] in phone_list:
                    print("\033[31;1mphone number %s 已存在,无法插入到数据库!\033[0m"%sql_list[2])
                else:
                    line_num=[]
                    with open(staff_table.txt, "r+", encoding="utf-8")as f:
                        for line in f:
                            line_list = line.strip().split(",")
                            line_num.append(line_list[0])
                        row_id = str(int(line_num[-1]) + 1)
                        sql_list.insert(0, row_id)
                        sql_list = ,.join(sql_list)
                        f.write(sql_list+\n)
                        print(sql_list +\n "添加成功!")
    else:
        print ("\033[31;1mSQL 语法有误!\033[0m")


def delete(sql):
    """
    删除语法:delete from staff_table where staff_id = 12
    """
    if len(sql) == 0 or delete not in sql.lower():
        print ("\033[31;1m输入为空或语句有问题,请输入正确的SQL语句!\033[0m")
        return

    sql_list = sql.split()
    if sql.lower().replace( ,‘‘) == "deletefromstaff_tablewherestaff_id=%s"%sql_list[-1]:
        line_write=[]
        with open(staff_table.txt, encoding="utf-8") as f:
            for line in f:
                i = line.strip().split(",")
                if sql_list[-1] == i[0]:
                    #把所有要符合条件的行加入到列表中
                    line_write.append(i)
                else:
                    continue 
        with open(staff_table.txt, encoding="utf-8")as f_read,open(staff_table_bak.txt, "a+", encoding="utf-8")as f_write:
            for line in f_read:
                for row1 in line_write:
                    #把列表拼接成行
                    row2=,.join(row1)
                    if row2 in line:
                        print (row2)
                        line = line.replace(row2, "").strip()
                f_write.write(line)
               
        os.remove(staff_table.txt)
        os.rename(staff_table_bak.txt,staff_table.txt)
        print("删除成功,共删除%s条"%len(line_write))
        return
    else:
        print("\033[31;1mSQL 语法有误!\033[0m") 
        return


def update(sql):
    """
    修改语法:UPDATE staff_table SET dept="Market" WHERE where dept = "IT"
    """
    if len(sql) == 0 or update not in sql.lower():
        print ("\033[31;1m输入为空或语句有问题,请输入正确的SQL语句!\033[0m")
        return
    field_values = sql.lower().split()
    sql_list = sql.split()

    if sql.lower().replace( ,‘‘) == "updatestaff_tablesetdept=%swherewheredept=%s"%(field_values[field_values.index("set")+1].split("=")[1],field_values[-1]):        
        with open(staff_table.txt, encoding="utf-8") as f_read, open(staff_table_tmp.txt, "w", encoding="utf-8")as f_write:
            count=0
            for line in f_read:
                if sql_list[-1].replace(",‘‘) in line:  
                    line = line.replace(sql_list[-1].replace(",‘‘),sql_list[sql_list.index(SET)+1].split(=)[1].replace(",‘‘))
                    print (line)
                    count += 1
                f_write.write(line)
        os.remove(staff_table.txt)
        os.rename(staff_table_tmp.txt,staff_table.txt)
        print("共成功修改%s条!"%count)
    else:
        print("\033[31;1mSQL 语法有误!\033[0m")
        return

def init(filename):
    if not os.path.exists(filename):
        with open(filename,mode=w,encoding=utf-8)as f:
            data = ["1,liubei,42,13812345678,IT,2013-04-01\n",
                    "2,guanyu,30,13899999999,HR,2015-05-03\n",
                    "3,zhangfei,25,13988888888,SALES,2016-04-22\n",
                    "4,zhaoyun,23,13288888888,IT,2013-04-01\n",
                    "5,张三,22,13812345677,Market,2017-06-18\n",
                    "9,李四,22,13812345675,IT,2017-06-18\n ",
                   "10,王五,22,13812345278,IT,2017-06-18\n",
                    "11,Alex Li,30,13812345685,IT,2013-04-01\n"
                   ]
            for line in data:
                f.write(line)


if __name__ == "__main__":
    msg = """
**********员工信息表程序***********    
    1:查询
    2:添加
    3:删除
    4:修改
    5:退出
***********************************
    """
    msg_dict = {
        "1": select,
        "2": insert,
        "3": delete,
        "4": update,
        "5": exit,
    }

    #初始化基础数据
    init(staff_table.txt)

    while True:
        print(msg)
        choice = input("输入序号>>:")
        if len(choice) == 0 or choice not in msg_dict: continue
        if choice == 1:
            print (
            ‘‘‘
            查询支持以下三种语句:
              查询语法一:select name,age from staff_table where age > 22
              查询语法二:select * from staff_table where dept = IT
              查询语法三:select  * from staff_table where enroll_date like "2013"
            ‘‘‘)  
        elif choice == 2:
             print (
             ‘‘‘   
             添加支持以下语句:
             insert into staff_table values (zhangsan,23,138888888888,IT,2017-06-18)
             ‘‘‘
             )
        elif choice == 3:
             print (
             ‘‘‘
             删除支持以下语句:   
             delete from staff_table where staff_id = 12
             ‘‘‘
             )
        elif choice == 4:
             print (
             ‘‘‘
             更新支持以下语句:   
             UPDATE staff_table SET dept="Market" WHERE where dept = "IT"
             ‘‘‘
             )
 
        if choice ==5:break
        sql = input("请输入sql语句:\nsql> ").strip()
        msg_dict[choice](sql)
View Code

 

二、模拟ATM系统

作业要求:

1. 指定最大透支额度
2. 可取款
3. 定期还款(每月指定日期还款,如15号)
4. 可存款
5. 定期出账单
6. 支持多用户登陆,用户间转账
7. 支持多用户
管理员账号
8. 管理员可添加账户、指定用户额度、冻结、解冻用户账户等

技术分享
#-*- coding:utf-8 -*-

import os
import getpass
import datetime
import re


def login():
    ‘‘‘
    登录
    ‘‘‘
    welcome_str = ‘‘‘
                                    欢迎来到ATM自动取款机系统
*******************************************************************************************************
请选择需要的操作:
1、用户登陆
2、管理员登陆
3、退出
*******************************************************************************************************
    ‘‘‘
    while True:
        print(welcome_str)
        opera_num = input(请选择要操作的编号(1-3):\n>>> ).strip()
        if opera_num.isdigit() and 0 < int(opera_num) < 4:
            return opera_num
        else:
            print(你的输入有误,请重新输入!)
            continue

def read_info(user_info):
    ‘‘‘
    将用户信息读至内存中
    ‘‘‘
    with open(user_info, mode=r, encoding=utf-8) as f:
        info_dict=f.read()
        return eval(info_dict)


def write_info(info_dict, user_info):
    ‘‘‘
    将用户信息写至用户文件中
    ‘‘‘
    with open(user_info, mode=w, encoding=utf-8) as f:
        f.write(str(info_dict))

def read_ubill(username):
    ‘‘‘
    将用户账单读取到内存
    ‘‘‘
    bill_name = username + _bill.txt
    bill_list = []
    with open(bill_name, mode=r, encoding=utf-8) as f:
        bill_list.clear()
        for line in f:
            bill_list.append(line.split(,)[0])
            bill_list.append(line.split(,)[1])
            bill_list.append(line.split(,)[2])
            bill_list.append(line.split(,)[3])
        return bill_list

def write_ubill(bill_list, username):
    ‘‘‘
    将用户账单写回文件
    ‘‘‘
    string=‘‘
    bill_name = username + _bill.txt
    with open(bill_name, mode=w, encoding=utf-8) as f:
        for index, i in enumerate(bill_list):
            if (index + 1) % 4 == 0:
                string = string + i + ,\n
            else:
                string = string + i + ,
        f.write(string)


def read_locked(user_locked):
    ‘‘‘
    将锁定用户读至内存
    ‘‘‘
    with open(user_locked, mode=r, encoding=utf-8) as f:
        locked_list = f.read()
        return eval(locked_list)


def write_locked(locked_list):
    ‘‘‘
    将内存写至锁定用户文件
    ‘‘‘
    with open(user_locked.txt, mode=w, encoding=utf-8) as f_lock:
        f_lock.write(str(locked_list))



def welcome_str():
    welcome_str = ‘‘‘
              欢迎来到ATM自动取款机系统
******************************************************
    1、存款
    2、取款
    3、转账
    4、显示账单
    5、修改密码
    6、退出
******************************************************
    ‘‘‘
    print(welcome_str)


def user_login(info_dict,locked_list):
    count = 0
    while True:
        username = input(请输入用户名(或者输入q退出):\n>>> ).strip()
        if username.lower() == q:
            break
        elif username == "":
            print ("\033[31;1m用户名不能为空 !\033[0m")
            continue
        elif username not in info_dict.keys():
            print ("\033[31;1m没有该用户 !\033[0m")
            continue
        elif username in locked_list:
            print ("\033[31;1m您输入的用户名已经被冻结,请联系管理员!\033[0m")
            continue 

        while True:
            password = getpass.getpass(请输入密码:\n>>> ).strip()
            if info_dict[username][0] == password:
                #welcome_str()
                return username
            else:
                count += 1

                if count >= 3:
                    locked_list.append(username)
                    write_locked(locked_list)
                    print("\033[31;1m您登陆失败的次数过多,该用户已经被冻结!\033[0m")
                    break               
                  
def user_operation(username):
    ‘‘‘
    用户选择操作
    ‘‘‘
    while True:
        welcome_str()
        choice_num = input(\n请输入操作编号1-6:\n>>> ).strip()
        if choice_num.isdigit() and 0 < int(choice_num) < 7:
            return (choice_num,username)
        else:
            print(您的输入的操作编号有误,请重新输入!)
            continue

def is_debt(info_dict, bill_list, username):
    ‘‘‘
    检查用户是否有透支
    ‘‘‘
    #15号自动还款
    if (int(str(datetime.date.today()).split(-)[2]) == 1) and (int(info_dict[username][3]) > 0):
        # 余额-透支 > 0
        if (int(info_dict[username][1]) - int(info_dict[username][3])) >= 0:
            debt_num = info_dict[username][3] 
            #用余额抵扣透支额 
            info_dict[username][1] = str(int(info_dict[username][1]) - int(info_dict[username][3]))
            info_dict[username][3] = 0 
            bill_list.append(str(datetime.date.today()))
            bill_list.append(0)
            bill_list.append(debt_num)
            bill_list.append(info_dict[username][1])
            print(您好,今天的日期是 + str(datetime.date.today()) + ,今日为还款日,系统已经自动为您还款! +
                  目前您的余额为: + info_dict[username][1])
        else:
            print(您好,今天的日期是 + str(datetime.date.today()) +
                  ,今日为还款日,您的余额不足以还清欠款!请及时存款还款!\n目前您的余额为: + info_dict[username][1])
    elif (int(str(datetime.date.today()).split(-)[2]) < 15) and (int(info_dict[username][3]) > 0):
        print(您好,今天的日期是 + str(datetime.date.today()) + \n您目前欠款金额为: + info_dict[username][3] +
              ,\n请在本月15日前还清欠款,否则系统将自动还款!)


def admin_login():
    ‘‘‘
    管理员操作:默认管理员用户名:admin,密码:123456
    ‘‘‘
    while True:
        username = input(请输入管理员用户名,默认admin,(或者输入q退出):\n>>> ).strip()
        if username.lower() == q:
            break 
        password = input(请输入管理员密码,默认123456:\n>>>).strip()
        if username == admin and password == 123456:
            return True 
        else:
            continue


def admin_operation():
    ‘‘‘
    管理员操作
    ‘‘‘
    while True:
        welcome_str = ‘‘‘
    欢迎来到ATM自动取款机-管理员功能区
*********************************************
1、添加用户
2、冻结用户
3、解封用户
4、设定用户额度
5、退出
*********************************************
            ‘‘‘
        print(welcome_str)
        choice_num = input(\n请输入操作编号1-5:\n>>> ).strip()
        if choice_num.isdigit() and 0 < int(choice_num) < 6:
            return choice_num
        else:
            print(您输入的操作编号有误,请重新输入!)
            continue


def deposit_money(info_dict, bill_list, username):
    ‘‘‘
    存款
    ‘‘‘
    while True:
        deposit_num = input(请输入存款金额(或者输入q退出):\n>>>).strip()
        if deposit_num.isdigit():
            print(当前余额为: + info_dict[username][1] + \n存入后余额为: + str(int(info_dict[username][1]) + int(deposit_num)))
            is_sure = input(是否确认存款(y/n)?\n>>>).strip()
            if is_sure.lower() == y:
                info_dict[username][1] = str(int(info_dict[username][1]) + int(deposit_num))
                bill_list.append(str(datetime.date.today()))
                bill_list.append(deposit_num)
                bill_list.append(0)
                bill_list.append(info_dict[username][1])
            elif is_sure.lower() == n:
                break
            else:
                print(输入有误,请重新确认!)
                continue
        elif deposit_num.lower() == q:
            break
        else:
            print(存款金额输入有误,请重新输入!)
            continue


def draw_money(info_dict, bill_list, username):
    ‘‘‘
    取款
    info_dict={‘test‘: [‘123456‘, ‘1222‘, ‘10000‘, ‘0‘]}
    ‘‘‘
    while True:
        draw_num = input(请输入取款金额(或者输入q退出):\n>>>).strip()
        # 余额+额度-取款金额>=0
        if draw_num.isdigit() and ((int(info_dict[username][1]) + int(info_dict[username][2]) - int(draw_num)) >= 0):
            print(当前余额为: + info_dict[username][1] + \n取款后后余额为: + str(int(info_dict[username][1]) - int(draw_num)))
            is_sure = input(是否确认取款(y/n)?\n>>>).strip()
            if is_sure.lower() == y:
                # 余额 < 取款金额 < (余额+额度)
                if (int(info_dict[username][1]) < int(draw_num) < (
                            int(info_dict[username][1]) + int(info_dict[username][2]))):
                    info_dict[username][1] = 0  # 余额设置为0
                    info_dict[username][3] = int(info_dict[username][3]) + int(draw_num) - int(info_dict[username][1])  # 透支额=取款额-余额
                    bill_list.append(str(datetime.date.today()))
                    bill_list.append(0)
                    bill_list.append(draw_num)
                    bill_list.append(0)
                # 余额 > 取款金额
                elif (int(info_dict[username][1]) >= int(draw_num)):
                    info_dict[username][1] = str(int(info_dict[username][1]) - int(draw_num))
                    bill_list.append(str(datetime.date.today()))
                    bill_list.append(0)
                    bill_list.append(draw_num)
                    bill_list.append(str(int(info_dict[username][1])))
            elif is_sure.lower() == n:
                break
            else:
                print(输入有误,请重新确认!\n)
                continue
        elif draw_num.lower() == q:
            break
        # 取款金额超过了余额+最大额度了
        elif draw_num.isdigit() and (
            (int(info_dict[username][1]) + int(int(info_dict[username][2]) - int(draw_num))) < 0):
            print(取款金额大于当前余额与最大额度之和,请重新输入!\n用户: + username +
                   当前余额为: + info_dict[username][1] + \n)
            continue
        else:
            print(取款金额输入有误,请重新输入!\n)
            continue


def trans_money(info_dict, bill_list, username):
    ‘‘‘
    转账
    ‘‘‘
    while True:
        for index, i in enumerate(info_dict.keys()):
            if not i == username:
                if (index + 1) % 5 == 0:
                    print(str(i) + \n, end=‘‘)
                else:
                    print(str(i) + ||, end=‘‘)
        trans_choice = input(\n请输入向哪位用户转账(或者输入q退出):\n>>>).strip()
        if trans_choice in info_dict.keys():  # 选择转账的用户是否在这个字典中
            trans_num = input(请输入转账金额:\n>>>).strip()
            if (trans_num.isdigit()) and (int(trans_num) <= int(info_dict[username][1])):
                is_sure = input(是否确定向用户  + trans_choice +  转账: + trans_num +  ? (y/n)\n>>>)
                if is_sure.lower() == y:
                    # 给转账用户的余额加钱
                    info_dict[trans_choice][1] = str(int(info_dict[trans_choice][1]) + int(trans_num))
                    # 给自己的账号余额减钱
                    info_dict[username][1] = str(int(info_dict[username][1]) - int(trans_num))
                    bill_list.append(str(datetime.date.today()))
                    bill_list.append(0)
                    bill_list.append(trans_num)
                    bill_list.append(str(int(info_dict[username][1])))
                    trans_name = trans_choice + _bill.txt
                    with open(trans_name, mode=w, encoding=utf-8) as f:
                        f.write(str(datetime.date.today()) + , + trans_num + , + 0 + , + str(
                            info_dict[trans_choice][1]) + ,)
                    print(转账成功!)
                elif is_sure.lower() == n:
                    continue
                else:
                    print(输入有误,请重新输入!\n)
                    continue
            else:
                print(您输入的金额有误或超出现有余额,请重新输入!\n)
                continue
        elif trans_choice.lower() == q:
            break
        else:
            print(你输入的用户名有误,请重新输入!\n)
            continue


def show_bill(username):
    ‘‘‘
    显示账单
    ‘‘‘
    while True:
        choice_bill = input(\n请输入查询的账单年月,如2017-05(或者输入q退出):\n>>>).strip()
        if re.match(r"^[0-9]{6}", choice_bill.replace(-, ‘‘)):
            print(choice_bill.rjust(15, -) +   + 用户: + username +  账单明细.ljust(15, -))
            print(交易日期 | 存款金额 | 取款金额 | 余额)
            bill_name = username + _bill.txt
            with open(bill_name, mode=r, encoding=utf-8) as f:
                for line in f:
                    if line.startswith(choice_bill):
                        print(line.replace(,,      ), end="")
        elif choice_bill.lower() == q:
            break
        else:
            print(您输入的查询账单年月有误,请重新输入!)
            continue


def change_pwd(info_dict, username):
    ‘‘‘
    修改用户密码
    ‘‘‘
    flag = False
    while True:
        for k, v in info_dict.items():
            if k == username:
                old_pwd = input(请输入用户  + username + 原密码:\n>>>).strip()
                if old_pwd == v[0]:
                    new_pwd = input(请输入新密码:\n>>>).strip()
                    v[0] = new_pwd
                    print(密码修改成功!)
                    flag = True
                    break
                else:
                    print(您输入的原密码不正确,请重新输入!)
                    break
            else:
                continue
        if flag:
            break


def add_user(info_dict):
    ‘‘‘
    添加用户
    ‘‘‘
    new_list = []
    while True:
        new_user = input(请输入想要添加的用户名(或者输入q退出):\n>>>).strip()
        if new_user.lower() == q:
            break
        if new_user in info_dict.keys():
            print(此用户名已经存在!请重新输入!)
            continue
        if new_user == "":
            print(用户名不能为空!请重新输入!)   
            return
        else:
            new_pwd = input(请设置用户  + new_user + 密码:\n>>>).strip()
            if new_pwd == "":
                print(用户密码不能为空!请重新输入!)
                return
            new_list.append(new_pwd)
            new_list.append(0)
            new_list.append(10000)
            new_list.append(0)
            info_dict[new_user] = new_list.copy()
            print(用户  + new_user + 添加成功!默认用户额度为10000!)
            #初始化用户账单
            if not os.path.isfile(%s_bill.txt%new_user):
                with open(new_user + _bill.txt, mode=w, encoding=utf-8) as f:
                    bill=‘‘
                    f.write(bill)


def freeze_user(info_dict, locked_list):
    ‘‘‘
    冻结用户
    ‘‘‘
    while True:
        print(当前存在的用户如下:)
        for index, i in enumerate(info_dict.keys()):
            if (index + 1) % 5 == 0:
                print(str(i) + \n, end=‘‘)
            else:
                print(str(i) + ,, end=‘‘)
        user_lock = input(\n请输入要冻结的用户名(或者输入q退出):\n>>>).strip()
        if user_lock in info_dict.keys():
            is_sure = input(确认要冻结用户 %s ? (y/n)%user_lock).strip()
            if is_sure.lower() == y:
                if user_lock in locked_list:
                    print (用户%s已经被冻结了%user_lock)
                else:
                    locked_list.append(user_lock)
                    print(冻结用户 %s 成功!\n%user_lock)
            elif is_sure.lower() == n:
                break
            else:
                print(您的输入有误,请重新输入!)
                continue
        elif user_lock.lower() == q:
            break
        else:
            print(您输入的用户名不存在,请重新输入!)
            continue

def deblock_user(info_dict, locked_list):
    ‘‘‘
    解冻用户
    ‘‘‘
    while True:
        print(被锁定的用户如下:)
        for index, i in enumerate(locked_list):
            if (index + 1) % 5 == 0:
                print(str(i) + \n, end=‘‘)
            else:
                print(str(i) + ,, end=‘‘)
        unlock_user = input(\n请输入要解冻的用户名(或者输入q退出):\n>>>).strip()
        if unlock_user in info_dict.keys():
            is_sure = input(确认要解冻用户 %s ? (y/n)%unlock_user).strip()
            if is_sure.lower() == y:
                locked_list.remove(unlock_user)
                print(解冻用户 %s 成功!\n%unlock_user)
            elif is_sure.lower() == n:
                break
            else:
                print(您的输入有误,请重新输入!)
                continue
        elif unlock_user.lower() == q:
            break
        else:
            print(您输入的用户名不存在,请重新输入!)
            continue


def set_limit(info_dict):
    ‘‘‘
    指定用户额度
    ‘‘‘
    flag = False
    while True:
        print(当前存在的用户如下:)
        for index, i in enumerate(info_dict.keys()):
            if (index + 1) % 5 == 0:
                print(str(i) + \n, end=‘‘)
            else:
                print(str(i) + ||, end=‘‘)
        choice_user = input(\n请输入要修改额度的用户名(或者输入q退出):\n>>> ).strip()
        print (choice_user)
        if choice_user.lower() == q:
            break
        if choice_user in info_dict.keys():
            while flag == False:
                new_limit = input(请输入用户新额度:\n>>> ).strip()
                if new_limit and new_limit.isdigit():
                    info_dict[choice_user][2] = new_limit
                    print(用户额度修改成功!)
                    flag = True 
                else:
                    print(输入有误,请重新输入!)
                    continue

def init():
    ‘‘‘
    初始化用户数据
    ‘‘‘
    if not os.path.isfile(./user_info.txt):
        #用户名:[密码,余额,额度,透支金额]
        user = {
            test1: [123456, 1222, 10000, 0], 
            test2: [123456, 1222, 10000, 0],
            test3: [123456, 1222, 10000, 0]
        }
        with open(user_info.txt,mode=w,encoding=utf-8) as f:
            f.write(str(user))
    if not os.path.isfile(./user_locked.txt):
        lock=[]
        with open(user_locked.txt,mode=w,encoding=utf-8) as f:
            f.write(str(lock))
    for username in (test1,test2,test3):
        if not os.path.isfile(%s_bill.txt%username):
            with open(%s_bill.txt%username,mode=w,encoding=utf-8) as f:
                f.write(‘‘)


if __name__ == __main__:
    init()
    while True:
        userinfo = read_info(user_info.txt)
        userlock = read_locked(user_locked.txt)
        choice=login()
        # 普通用户登录
        if choice.strip() == 1:
            logged_user=user_login(userinfo,userlock)
            while logged_user != None:
                #用户选择操作的编号
                res = user_operation(logged_user)
                if res:
                    opera_num,username=res
                    userbill=read_ubill(username)
                else:
                    break
 
                # 存款
                if  opera_num.strip() == 1:
                    deposit_money(userinfo, userbill, username)
                    write_info(userinfo, user_info.txt)
                    write_ubill(userbill, username)
                    write_locked(userlock)
                # 取款
                elif opera_num.strip() == 2:
                    is_debt(userinfo, userbill, username)
                    draw_money(userinfo, userbill, username)
                    write_info(userinfo, user_info.txt)
                    write_ubill(userbill, username)
                #转账
                elif opera_num.strip() == 3:
                    trans_money(userinfo, userbill, username)
                    write_info(userinfo, user_info.txt)
                    write_ubill(userbill, username)
                    write_locked(userlock)
                #显示账单
                elif opera_num.strip() == 4:
                    show_bill(username)
                #修改密码
                elif opera_num.strip() == 5:
                    change_pwd(userinfo, username)
                    write_info(userinfo, user_info.txt)
                #退出程序
                elif opera_num.strip() == 6:
                    print(现在退出ATM自动取款机普通用户可操作界面!)
                    break
        #管理员登录
        elif choice.strip() == 2:
            res = admin_login()
            while res == True:
                admin_choice = admin_operation()
                if admin_choice.strip() == 1:
                    add_user(userinfo)
                    write_info(userinfo, user_info.txt)

                elif admin_choice.strip() == 2:
                    freeze_user(userinfo, userlock)
                    write_locked(userlock) 
               
                elif admin_choice.strip() == 3:
                    deblock_user(userinfo, userlock)
                    write_locked(userlock)

                elif admin_choice.strip() == 4:
                    set_limit(userinfo)
                    write_info(userinfo, user_info.txt)

                elif admin_choice.strip() == 5:
                    print(管理程序退出!谢谢光临!)
                    break
        #退出登录
        elif choice.strip() == 3:
            print(欢迎您下次光临ATM自动取款机,再见!)
            exit()

        else:
            print(您的输入有误,请重新输入!)
            continue
View Code

 

函数作业

标签:upd   exist   冻结   split()   set   money   hang   string   一键   

原文地址:http://www.cnblogs.com/xingjiancheng/p/7526204.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!