成功最有效的方法就是向有经验的人学习!

ATM购物车

import os
import random

# 获取商品数据
def get_product():
    pr = []
    with open('product.txt', mode='rt', encoding='utf-8') as f:
        for fi in f:
            l = fi.strip().split(",")
            if "." in l[2]:
                l[2] = float(l[2])
            else:
                l[2] = int(l[2])
            pr.append(l)
    return pr

# 获取用户数据
def get_db():
    with open('db.txt', mode='rt', encoding='utf-8') as f:
        return f.read().splitlines()

# 登陆验证
def check_login(func):
    db = get_db()

    def inner(*args, **kwargs):
        global shop_is_login,user_name,cart
        if not shop_is_login:
            in_user = input("请输入用户名:").strip()
            in_pwd = input("请输入密码:").strip()
            for ui in db:
                u = ui.split(",")
                if in_user == u[0] and in_pwd == u[1]:
                    shop_is_login = True
                    user_name = in_user
                    if in_user not in cart:
                        cart[user_name]=[]
                    res = func(*args, **kwargs)
                    return res
        else:
            res = func(*args, **kwargs)
            return res

    return inner

# 生成商品列表
def show_product():
    p = get_product()
    print("商品列表".center(50, "="))
    for pi in p:
        print("{p_id}\t{p_name}\t\t\t{price}".format(p_id=pi[0], p_name=pi[1], price=pi[2]))

# 添加购物车
def add_cart(p_id, cartd, action="add"):
    p_db = get_product()
    for pp in p_db:
        if p_id in pp:
            if action == "add":
                for cd in cartd:
                    if p_id == cd[0]:
                        cd[3] += 1
                        break
                else:
                    tp = pp
                    tp.append(1)
                    cart.append(tp)
                    # print(cart[-1])
            return pp
    return 0

# 银行认证及扣款
def bank(money_list, user_id, buy_money):
    users, moneys = money
    if user_id == users:
        if buy_money <= money[1]:
            money[1] -= buy_money
            return 1
        print("余额不足")
        return 0
    print("用户认证失败")
    return 0

# 打印购物车
def show_cart(s):
    print("已购商品".center(50, "="))
    sum = 0
    for cart_end in s:
        sum += (cart_end[2] * cart_end[3])
        print("{p_id}\t{p_name}\t\t\t{price}\t\t{num}\t\t\t{sum_price}".format(p_id=cart_end[0], p_name=cart_end[1],
                                                                               price=cart_end[2], num=cart_end[3],
                                                                               sum_price=cart_end[2] * cart_end[3]))
    print("总花费:{}".format(str(sum)))

# ========================银行相关

# 银行卡验证
def bank_auth(fun):
    db = load_bank_db()

    def inner(*args, **kwargs):
        res = ""
        err_sum = 0
        global tag
        while tag:
            if err_sum == 3:
                print("卡号密码连续输错三次,中止操作")
                tag = False
                break
            b_id = input("卡号:").strip()
            b_pwd = input("密码:").strip()
            res = login_bank(b_id, b_pwd)

            if res[0]:
                global user_bank, bank_id, user_b_money
                user_bank = res[1]
                user_b_money = res[2]
                bank_id = b_id
                res = fun(*args, **kwargs)
                break
            else:
                print("卡号或密码错误,请重试")
                err_sum += 1
                continue

        return res

    return inner

# 获取银行数据
def load_bank_db():
    lbd = []
    with open('bank.txt', "rt", encoding="utf-8") as f1:
        for bd in f1:
            l1 = bd.strip().split(",")
            if l1[2].isdigit():
                l1[2] = int(l1[2])
            else:
                l1[2] = float(l1[2])
            lbd.append(l1)
    return lbd

# 获取信用卡数据
def load_xyk_db():
    lbd = []
    with open('xyk.txt', "rt", encoding="utf-8") as f1:
        for bd in f1:
            l1 = bd.strip().split(",")
            l1[2] = float(l1[2])
            l1[3] = float(l1[3])
            lbd.append(l1)
    return lbd

def login_bank(user, pwd):
    db = load_bank_db()
    for i in db:
        if user in i:
            if pwd == i[1]:
                return 1, i[3], i[2]
    else:
        return 0, 0

# 显示帐户信息
@bank_auth
def bank_info():
    db = load_bank_db()
    for i in db:
        if bank_id in i:
            print("卡号:{c_id}\n余额:{c_price}".format(c_id=i[0], c_price=str(i[2])))
            input("按任意键继续...")

def get_money(b_id, money):
    db = load_bank_db()
    print(db)
    for i in db:
        if b_id in i:
            if int(money) > i[2]:
                # print("余额不足")
                return "-1", i[2]
            else:
                i[2] -= int(money)
                print(db)
                return "ok", i[2]

def user_money(user_id, money):
    with open("db.txt", "rt", encoding="utf-8") as f1, open("db.txt.swap", "wt", encoding="utf-8") as f2:
        for i in f1:

            res = i.strip().split(",")
            if user_id == res[0]:
                res[2] = int(res[2]) + int(money)
                newstr = ",".join(str(j) for j in res)
                f2.write("%s\n" % newstr)
                continue
            f2.write(i)
    os.remove("db.txt")
    os.rename("db.txt.swap", "db.txt")

def save_bank(b_id, l8, action="N"):
    with open("bank.txt", "rt", encoding="utf-8") as f1, open("bank.txt.swap", "wt", encoding="utf-8") as f2:
        for i in f1:

            res = i.strip().split(",")
            if b_id == res[0]:
                if action == "add":
                    res[2] = float(res[2]) + float(l8)
                else:
                    res[2] = l8
                newstr = ",".join(str(j) for j in res)
                f2.write("%s\n" % newstr)
                continue
            f2.write(i)
    os.remove("bank.txt")
    os.rename("bank.txt.swap", "bank.txt")
    return 1

# 购物
@check_login
def buy():
    global cart
    db = get_product()
    show_product()
    p_id = input("请输入商品编号:").strip()
    for i in db:
        if p_id in i:  # 输入的商品编号在列表中存在,有效
            if user_name in cart:
                for k in cart[user_name]:
                    if p_id in k:  # 输入的商品编号已加入过购物车
                        k[3]+=1
                        break
                else:
                    i.append(1)
                    cart[user_name].append(i)
            break

    else:
        print("商品编号错误")

# 查看购物车
@check_login
def show_cart():
    global cart
    print("购物车".center(50,"="))
    print(id(cart),cart)
    # for i in cart:
        # print("{p_id}\t{p_name}\t{p_price}\t{p_num}\t{p_sum}".format(p_id=i[0], p_name=i[1], p_price=i[2], p_num=i[3],
        #                                                              p_sum=float(i[2]) * int(i[3])))

# 结算购物车

def buyend():
    pass

# 查看订单
def show_order():
    pass

# 显示功能菜单
def show_menu(f):
    for k, v in f.items():
        print(k, v[0])

# 购物主程序
def shop():
    shop_menu = {
        "1": ["购买商品", buy],
        "2": ["查看购物车", show_cart],
        "3": ["结算购物车", buyend],
        "4": ["查看订单", show_order],
        "8": ["返回主界面", None]
    }
    global tag, shop_is_login
    while tag:
        show_menu(shop_menu)
        cmd = input("请选择功能编号:").strip()
        if cmd == "8":
            # tag = False
            shop_is_login = False
            break
        elif cmd in shop_menu:
            shop_menu[cmd][1]()  # 进入功能
        else:
            print("功能不存在")
            continue

# 取款
@bank_auth
def qk():
    global user_b_money
    money = input("请输入取款金额:").strip()
    if money.replace(".", "", 1).isdigit():
        # 输入的金额是正确的,开始执行取款功能
        res = get_money(user_bank, money)
        if res[0] == "ok":
            print("取款:{c_id}元\n余额:{c_price}".format(c_id=money, c_price=res[1]))
            print(user_b_money)
            user_b_money = res[1]
            save_bank(bank_id, res[1])
            user_money(user_bank, money)
            print(user_b_money)

# 转账
@bank_auth
def zz():
    global bank_id, user_b_money
    des_bank_id = input("请输入对方银行卡号:").strip()
    t_money = input("请输入转账金额").strip()
    if not t_money.replace(".", "", 1).isdigit():
        print("金额不正确")
        return
    with open("bank.txt", "rt", encoding="utf-8") as f1, open("bank.txt.swap", "wt", encoding="utf-8") as f2:
        for i in f1:
            l = i.strip().split(",")
            if des_bank_id in l:  # 对方银行卡存在,开始转账
                if float(t_money) < user_b_money:  # 余额充足
                    l[2] = float(l[2]) + float(t_money)
            elif user_bank in l:
                if float(t_money) < user_b_money:  # 余额充足
                    l[2] = float(l[2]) - float(t_money)
                    print(user_b_money)
                    user_b_money = float(l[2])
                    print(user_b_money)
            newstr = ",".join(str(j) for j in l)
            f2.write("{}\n".format(newstr))
    os.remove("bank.txt")
    os.rename("bank.txt.swap", "bank.txt")

# 修改密码
def m_pwd():
    pass

# 存钱
@bank_auth
def cq():
    global user_b_money
    money = input("请输入存款金额:").strip()
    if money.replace(",", "", 1).isdigit():  # 金额格式正常
        if save_bank(bank_id, money, "add"):
            print(user_b_money)
            user_b_money += float(money)
            print(user_b_money)

# 还款
def hk():
    pass

# 信用卡
@bank_auth
def xyk():
    db = load_xyk_db()
    global user_bank
    for i in db:
        if user_bank in i:
            print("您在该行已申请信用卡")
            return
    xyk_bz = [1000.0, 2000.0, 3000.0, 5000.0, 8000.0, 10000.0, 15000.0, 20000.0, 25000.0, 30000.0, 50000.0, 100000.0]
    xyk_id = random.randint(630021001, 630021999)
    mone_limit = xyk_bz[random.randint(1, len(xyk_bz))]  # 系统生成信用卡额度
    newstr = "\n{user},{card_id},{count_money},{zd}".format(user=user_bank, card_id=xyk_id, count_money=mone_limit,
                                                            zd=0.0)
    print(newstr)
    with open("xyk.txt", "at", encoding="utf-8") as f:
        f.write(newstr)
    input("按任意键继续...")

# 信用卡账单
def xyk_zd():
    pass

# ATM主程序
def atm():
    atm_menu = {
        "0": ["显示账户信息", bank_info],
        "1": ["取款", qk],
        "2": ["转账", zz],
        "3": ["修改密码", m_pwd],
        "4": ["存钱", cq],
        "5": ["还款", hk],
        "6": ["申请信用卡", xyk],
        "7": ["信用卡帐单", xyk_zd],
        "8": ["返回主菜单", None]
    }

    global tag
    while tag:
        show_menu(atm_menu)
        cmd = input("请选择功能编号:").strip()
        if cmd == "8":
            # tag = False
            break
        elif cmd in atm_menu:
            atm_menu[cmd][1]()  # 进入功能
        else:
            print("功能不存在")
            continue

index_menu = {
    "1": ["购物中心", shop],
    "2": ["ATM机", atm],
    "b": ["退出", None]
}

bank_login = False  # 银卡验证成功标志<全局>
user_bank = ""  # 银行卡所属用户<全局>
bank_id = "0"  # 银行卡号<全局>
user_b_money = 0.00  # 银行卡余额<全局>
tag = True
shop_is_login = False  # 商城用户登陆成功标志<全局>
user_name = ""  # 商城用户<全局>
cart = {}  # 购物车
# print("init",id(cart))
while tag:
    show_menu(index_menu)
    cmd = input("请选择功能编号:").strip()
    if cmd == "b":
        tag = False
        break
    elif cmd in index_menu:
        index_menu[cmd][1]()  # 进入功能
    else:
        print("功能不存在")
        continue
1 2
赞(0) 打赏
未经允许不得转载:陈桂林博客 » ATM购物车
分享到

大佬们的评论 抢沙发

全新“一站式”建站,高质量、高售后的一条龙服务

微信 抖音 支付宝 百度 头条 快手全平台打通信息流

橙子建站.极速智能建站8折购买虚拟主机

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册