学习是一个逐步发现自己无知的过程!

Python练习题ATM

all_user_data = []  # 所有用户信息
current_user = None  # 记录用户登陆信息


# 处理用户文件
def load_data():
    """处理文件中的用户数据将,数据以字典的方式存入一个列表中。"""
    with open('user_db.txt', mode='rt', encoding='utf-8') as f:
        for line in f:
            line = line.strip("\n")
            if line == "\n": continue
            ls = line.split("|")
            user_dic = {
                "name": ls[0],
                "pwd": ls[1],
                "max": ls[2],
                "money": ls[3],
                "lock": ls[4],
            }
            print(user_dic)
            all_user_data.append(user_dic)  # 函数体内部的代码需要调用才会有值


# load_data()
# print(all_user_data)
# 获取输入的用户信息
def get_user(name):
    """根据用户输入的用户名取出用户"""
    load_data()
    for user in all_user_data:
        if user['name'] == name:
            # print(user['name'])
            return user


# 将文件写入磁盘
import os


def save_to_file():
    """将内存中用户操作的数据存到文件中"""
    with open('user_db.txt', mode='rt', encoding='utf-8') as f, \
            open('.user_db.txt.swp', mode='w+t', encoding='utf-8') as f1:
        for user in all_user_data:
            f1.write("|".join(user.values()))  # 列表转换为字符串并拼接值
            f1.write("\n")
        os.remove('user_db.txt')
        os.rename('.user_db.txt.swp', 'user_db.txt')


# 购物商场
def shop_center():
    print("shop center")


# 用于保存用户登陆成功的状态
def atm_login():
    while True:
        name = input("请输入用户名或q退出: ".rjust(20, "-")).strip()
        # pwd = input("请输入密码:").strip()
        if name == "q":
            break
        if not name:
            print("用户名为空,请重新输入。")
            continue
        pwd = input("请输入密码:".rjust(20, "-")).strip()
        if not pwd:
            print("密码为空,请重新输入。")
            continue
        user = get_user(name)
        print(user)
        if name == user["name"] and pwd == user["pwd"]:
            print("\n", "登陆成功".center(20, "*"), "\n")
            global current_user
            current_user = user
            return
        else:
            print("用户或密码错误,请重新输入。")


# atm_login()
# print(all_user_data)

#  装饰器:验证用户是否登陆,并返回值
def login_auth(func):
    def wrapper(*args, **kwargs):
        if current_user == None:
            print("请先登陆".center(50, " "))
            atm_login()
            if current_user:
                return func(*args, **kwargs)
        else:
            print("已登陆")
            return func(*args, **kwargs)

    return wrapper


#  提现取款功能
@login_auth
def withdraw():
    while True:
        print(f"当前余额{current_user['money']}元\n")
        money = input("请输入提款金额或q退出:").strip()
        if money == "q": break
        if not money.isdigit():
            print("必须输入整数")
            continue
        money = int(money)

        opt = money * 0.05
        print(f"所需手续费{opt}")
        user_money = float(current_user["money"])
        if money + opt > user_money:
            print("余额不足,请重新输入")
            continue
        current_user["money"] = str(user_money - money - opt)  # 总金额减去取款金额以及手续费
        save_to_file()  # 调用函数将数据写入文件中
        print(f"取款成功本次取款: {money},手续费{opt},余额{current_user['money']}")
        return


# 转账功能
@login_auth
def transfer():
    while True:
        account = input("请输入对方用户名:").strip()
        to_user = get_user(account)  # 调用获取用户模块获取到用户信息
        if not to_user:
            print("对方账户/用户不存在,请查证后重新输入。")
            continue
        print(f"当前余额为{current_user['money']}")
        money = input("请输入转账金额或q退出: ").strip()
        if money == "q": break
        money = str_to_num(money)
        if not money:
            print("你输入的不是数字,请重新输入。")
            continue
        user_money = float(current_user['money'])
        if money > user_money:
            print("余额不足,请重新输入。")
            continue
        # 减去转账用户的余额
        current_user['money'] = str(user_money - money)
        # 增加对方账户余额
        to_user['money'] = str(float(to_user['money']) + money)
        save_to_file()
        print("转账成功")
        return


def str_to_num(text):
    '''将输入的字符串(input输入默认为字符串类型)转换为数字'''
    if text.isdigit():
        return int(text)
    if "." in text:
        ts = text.split(".")
        if len(ts) == 2:
            if ts[0].isdigit() and ts[1].isdigit():
                return float(text)


# 还款功能
@login_auth
def repayment():
    print(f"您当前欠款{str_to_num(current_user['max']) - str_to_num(current_user['money'])}")
    while True:
        print("还款")
        money = input("请输入还款金额或q退出:")
        if money == "q": break
        money = str_to_num(money)
        if not money:
            print("输入有误,请重新输入。")
            continue
        current_user["money"] = str(str_to_num(current_user["money"]) + money)
        save_to_file()
        print("还款成功")
        return


# 注册功能
def registered():
    while True:
        name = input("请输入注册用户名或q退出:".rjust(20, "-")).strip()
        if name == "q": break
        if not name:
            print("用户名不能为空。")
            continue
        user = get_user(name)
        if user:
            print("用户名以存在,请重新输入。")
            continue
        pwd = input("请输入密码:").strip()
        if not pwd:
            print("密码不能为空。")
            continue
        if pwd != input("请再次输入密码:").strip():
            print("两次密码输入不一致。")
            continue
        new_user = {"name": name, "pwd": pwd, "max": "15000", "money": "2000", "lock": "0"}
        all_user_data.append(new_user)
        print(f"{name}:用户创建成功")
        save_to_file()
        return


# 启动菜单

func_dict = {
    "1": ["注册", registered],
    "2": ["登陆", atm_login],
    "3": ["提现", withdraw],
    "4": ["转账", transfer],
    "5": ["还款", repayment],
    "q": ["退出"]
}


def start():
    # 启动菜单
    while True:
        for ke_y, val in func_dict.items():
            print("\t\t", ke_y, "\t", val[0])
        choice = input(f"请输入操作指令的编号,q退出:").strip()
        if choice == "q": break
        if choice in func_dict:
            func_dict[choice][1]()
        else:
            print("指令输入错误")


start()

 

赞(0)
未经允许不得转载:劉大帥 » Python练习题ATM

你的评论可能会一针见血! 抢沙发

登录

找回密码

注册