• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

python 模拟普通用户和管路员登录购物系统小程序

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

程序功能描述如下:不同角色登录,普通用户可以查看商品购买商品、查看购物车和余额、退出;管理员可以充值,可以添加商品、退出

用户信息字典格式:

{
  'pp1': {'passwd': '123', 'role': '1', 'money': 97738.5, 'carts': ['MAC', 'MI', 'MAC', 'KKK', 'HHH', 'LLL', 'LLL', 'LLL', 'YYY', 'LLL']},
  'pp2': {'passwd': '123', 'role': '2', 'money': 14435.76, 'carts': ['vivo', 'vivo', 'MAC']}
}

商品信息字典格式:

{
  'MAC': {'id': '3894710', 'price': 31233.22}, 'vivo': {'id': '1762774', 'price': 1888.0},
  'MI': {'id': '1762775', 'price': 2888.0}, 'HHH': {'id': '7053921', 'price': 12312},
  'KKK': {'id': '2789035', 'price': 123.22}, 'YYY': {'id': '2936504', 'price': 254.22},
  'LLL': {'id': '6091483', 'price': 231.2}, 'LOVONO': {'id': '7631802', 'price': 12321.22}
}

 


#role是1的话,代表管理员,2代表普通用户
#普通用户:
#1、查看所有的商品
#2、输入商品名称购买商品,购买完了之后要加到自己的购物车里面,钱要减去
#3、可以查看自己购物车和余额,你已经买了xx东西,你还xxx钱
#4、退出
#管理员,1、添加商品,商品名称,商品价格
2、充值,输入用户名,给他加钱
3、退出

程序实现如下:
# 登录
def login(u_name, u_pass):
    "用户登录"
    u_name = str(u_name)
    u_pass = str(u_pass)
    if not u_name or not u_pass:
        print("error,用户名或密码不能为空!")
    else:
        user_data = {}  # 个人账户信息,用于登录成功后返回
        with open('users.txt', 'r', encoding='utf-8') as fr:
            fr.seek(0)
            user_info = eval(fr.read())
            fr.close()
            if u_name not in user_info:
                print("error,用户名不存在!")
            elif u_pass != user_info[u_name]['passwd']:
                print("error,输入密码错误!")
            else:
                user_data[u_name] = user_info[u_name]
                print('success,登录成功,用户信息:', user_data)
                return user_data

# 查看所有商品
def get_goods():
    "查询所有商品"
    with open('goods.txt', 'r', encoding='utf-8') as fr:
        fr.seek(0)
        goods_info = eval(fr.read())
        fr.close()
        print('success,查询所有商品成功,商品信息:', goods_info)
        return goods_info

# 购买商品
def bug_goods(u_name, g_name):
    "用户购买商品"
    g_name = str(g_name)
    u_name = str(u_name)
    if not g_name or not u_name:
        return 'error,用户名或商品名称不能为空'
    goods_info = get_goods()
    if g_name not in goods_info:
        return 'error,商品%s不存在' % g_name
    else:
        with open('users.txt', 'a+', encoding='utf-8') as fa:
            fa.seek(0)
            user_info = eval(fa.read())
            if user_info[u_name]['money'] - goods_info[g_name]['price'] < 0:
                return 'error,用户余额不足'
            u_pass = user_info[u_name]['passwd']
            u_role = user_info[u_name]['role']
            u_money = user_info[u_name]['money'] - goods_info[g_name]['price']
            u_money = round(u_money, 2)
            u_carts = user_info[u_name]['carts']
            u_carts.append(g_name)
            user_info[u_name] = {'passwd': u_pass, 'role': u_role, 'money': u_money, 'carts': u_carts}
            fa.seek(0)
            fa.truncate()
            fa.flush()
            fa.write(str(user_info))
            fa.close()
            return 'success,购买:{goods} 成功,购物车商品:{carts}'.format(goods=g_name, carts=u_carts)

# 查询用户购物车和余额
def get_carts_money(u_name):
    "查询用户购物车、余额"
    u_name = str(u_name)
    if not u_name:
        return 'error,用户名不能为空'
    else:
        with open('users.txt', encoding='utf-8') as f:
            f.seek(0)
            user_info = eval(f.read())
            f.close()
            u_carts = user_info[u_name]['carts']
            u_money = user_info[u_name]['money']
        return 'success,查询用户购物车和余额成功,用户名:{name},购物车:{carts} ,账户余额:{money}元'.format(name=u_name, carts=u_carts, money= u_money)

# 添加商品
def add_goods(g_name, g_price):
    "添加商品"
    import string, random
    src_id = string.digits
    g_id = ''.join(random.sample(src_id, 7))
    g_name = str(g_name)
    if not g_name:
        return 'error,添加商品失败,商品名称必须输入'
    try:
        price = round(float(g_price), 2)
        if price <= 0:
            return 'error,添加商品失败,商品价格须大于0'
        with open('goods.txt', 'a+', encoding='utf-8') as fa:
            fa.seek(0)
            goods_info = eval(fa.read())
            goods_data = {g_name: {'id': g_id, 'price': price}}
            goods_info.update(goods_data)
            fa.seek(0)
            fa.truncate()
            fa.flush()
            fa.write(str(goods_info))
            fa.close()
        return 'success,添加商品:{goods}成功'.format(goods=goods_data)
    except ValueError:
        return 'error,添加商品失败,商品价格输入格式错误'

# 用户充值
def recharge(u_name, amount):
    "输入用户名给用户充值"
    u_name = str(u_name)
    try:
        u_amount = round(float(amount), 2)
        if u_amount <= 0:
            return 'error,充值金额须大于0'
        with open ('users.txt', 'a+', encoding='utf-8') as f:
            f.seek(0)
            user_info = eval(f.read())
            if u_name not in user_info:
                return 'error,用户名不存在'
            u_pass = user_info[u_name]['passwd']
            u_role = user_info[u_name]['role']
            u_money = user_info[u_name]['money']+u_amount
            u_carts = user_info[u_name]['carts']
            user_data = {u_name: {'passwd': u_pass, 'role': u_role, 'money': u_money, 'carts': u_carts}}
            user_info.update(user_data)
            f.seek(0)
            f.truncate()
            f.flush()
            f.write(str(user_info))
            f.close()
        return 'success,给用户:{user}充值成功,账户余额:{amount}元'.format(user=u_name, amount=user_data[u_name]['money'])
    except ValueError:
        return 'error,充值金额输入格式错误'

# 退出程序
def exit_sys():
    exit('退出程序')

# 普通用户
def user_role1(uName):
    choice = input('请输入你的选择:1:查看所有商品 2:购买商品 3:查看购物车和余额 4:退出\n').strip()
    if choice == '1':
        print(get_goods())
    elif choice == '2':
        goods_name = input("请输入要购买商品名称:\n").strip()
        print(bug_goods(uName, goods_name))
    elif choice == '3':
        print(get_carts_money(uName))
    elif choice == '4':
        exit_sys()
    user_role1(uName)

# 管理员用户
def user_role2():
    choice = input('请输入你的选择:1:添加商品 2:给用户充值 3:退出\n').strip()
    if choice == '1':
        goods_name = input("请输入你要添加的商品名称:\n").strip()
        goods_price = input("请输入添加商品价格:\n").strip()
        print(add_goods(goods_name, goods_price))
    elif choice == '2':
        u_name = input("请输入你要充值的用户名:\n").strip()
        amount = input("请输入充值金额:\n").strip()
        print(recharge(u_name, amount))
    elif choice == '3':
        exit_sys()
    user_role2()

# 主体部分
uName = input("请输入登录用户名:\n").strip()
uPass = input("请输入登录密码:\n").strip()
user = login(uName, uPass)
if user:  # 用户登录成功
    # 普通用户:
    if user[uName]['role'] == '1':
        user_role1(uName)
    # 管理员用户:
    elif user[uName]['role'] == '2':
        user_role2()
    else:
        print("用户角色不存在")
else:
    print("登录失败")
    exit_sys()

 上面的代码中,多次文件读写操作,代码重复太多,可以考虑把文件读写操作放在一个函数里面:

def open_file(file_name, content=None):
    "文件读写"
    f = open(file_name, 'a+', encoding='utf-8')
    f.seek(0)
    if content:
        f.truncate()
        f.write(str(content))
        f.flush()
        res = None
    else:
        res = eval(f.read())
    f.close()
    return res

 

这样优化以后的代码如下:

# 登录
def login(u_name, u_pass):
    "用户登录"
    u_name = str(u_name)
    u_pass = str(u_pass)
    if not u_name or not u_pass:
        print("error,用户名或密码不能为空!")
    else:
        user_data = {}  # 个人账户信息,用于登录成功后返回
        user_info = open_file('users.txt')
        if u_name not in user_info:
            print("error,用户名不存在!")
        elif u_pass != user_info[u_name]['passwd']:
            print("error,输入密码错误!")
        else:
            user_data[u_name] = user_info[u_name]
            print('success,登录成功,用户信息:', user_data)
            return user_data

# 查看所有商品
def get_goods():
    "查询所有商品"
    goods_info = open_file('goods.txt')
    print('success,查询所有商品成功,商品信息:', goods_info)
    return goods_info

# 购买商品
def bug_goods(u_name, g_name):
    "用户购买商品"
    g_name = str(g_name)
    u_name = str(u_name)
    if not g_name or not u_name:
        return 'error,用户名或商品名称不能为空'
    goods_info = open_file('goods.txt')
    if g_name not in goods_info:
        return 'error,商品%s不存在' % g_name
    else:
        user_info = open_file('users.txt')
        if user_info[u_name]['money'] - goods_info[g_name]['price'] < 0:
            return 'error,用户余额不足'
        u_pass = user_info[u_name]['passwd']
        u_role = user_info[u_name]['role']
        u_money = user_info[u_name]['money'] - goods_info[g_name]['price']
        u_money = round(u_money, 2)
        u_carts = user_info[u_name]['carts']
        u_carts.append(g_name)
        user_info[u_name] = {'passwd': u_pass, 'role': u_role, 'money': u_money, 'carts': u_carts}
        open_file('users.txt',user_info)
        return 'success,购买:{goods} 成功,购物车商品:{carts}'.format(goods=g_name, carts=u_carts)

# 查询用户购物车和余额
def get_carts_money(u_name):
    "查询用户购物车、余额"
    u_name = str(u_name)
    if not u_name:
        return 'error,用户名不能为空'
    else:
        user_info = open_file('users.txt')
        u_carts = user_info[u_name]['carts']
        u_money = user_info[u_name]['money']
        return 'success,查询用户购物车和余额成功,用户名:{name},购物车:{carts} ,账户余额:{money}元'.format(name=u_name, carts=u_carts, money= u_money)

# 添加商品
def add_goods(g_name, g_price):
    "添加商品"
    import string, random
    src_id = string.digits
    g_id = ''.join(random.sample(src_id, 7))
    g_name = str(g_name)
    if not g_name:
        return 'error,添加商品失败,商品名称必须输入'
    try:
        price = round(float(g_price), 2)
        if price <= 0:
            return 'error,添加商品失败,商品价格须大于0'
        goods_info = open_file('goods.txt')
        goods_data = {g_name: {'id': g_id, 'price': price}}
        goods_info.update(goods_data)
        open_file('goods.txt', goods_info)

        return 'success,添加商品:{goods}成功'.format(goods=goods_data)
    except ValueError:
        return 'error,添加商品失败,商品价格输入格式错误'

# 用户充值
def recharge(u_name, amount):
    "输入用户名给用户充值"
    u_name = str(u_name)
    try:
        u_amount = round(float(amount), 2)
        if u_amount <= 0:
            return 'error,充值金额须大于0'
        user_info = open_file('users.txt')
        if u_name not in user_info:
            return 'error,用户名不存在'
        u_pass = user_info[u_name]['passwd']
        u_role = user_info[u_name]['role']
        u_money = user_info[u_name]['money']+u_amount
        u_carts = user_info[u_name]['carts']
        user_data = {u_name: {'passwd': u_pass, 'role': u_role, 'money': u_money, 'carts': u_carts}}
        user_info.update(user_data)
        open_file('users.txt',user_info)
        return 'success,给用户:{user}充值成功,账户余额:{amount}元'.format(user=u_name, amount=user_data[u_name]['money'])
    except ValueError:
        return 'error,充值金额输入格式错误'

# 退出程序
def exit_sys():
    exit('退出程序')

# 普通用户
def user_role1(uName):
    choice = input('请输入你的选择:1:查看所有商品 2:购买商品 3:查看购物车和余额 4:退出\n').strip()
    if choice == '1':
        print(get_goods())
    elif choice == '2':
        goods_name = input("请输入要购买商品名称:\n").strip()
        print(bug_goods(uName, goods_name))
    elif choice == '3':
        print(get_carts_money(uName))
    elif choice == '4':
        exit_sys()
    user_role1(uName)

# 管理员用户
def user_role2():
    choice = input('请输入你的选择:1:添加商品 2:给用户充值 3:退出\n').strip()
    if choice == '1':
        goods_name = input("请输入你要添加的商品名称:\n").strip()
        goods_price = input("请输入添加商品价格:\n").strip()
        print(a 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap