• 购物车


    
    
    '''
    1. 用户先给自己的账户充钱:比如先充3000元。
    2. 页面显示 序号 + 商品名称 + 商品价格,如:
            1 电脑 1999
            2 鼠标 10
            …
            n 购物车结算
    3. 用户输入选择的商品序号,然后打印商品名称及商品价格,并将此商品,添加到购物车,用户还可继续添加商品。
    4. 如果用户输入的商品序号有误,则提示输入有误,并重新输入。
    5. 用户输入n为购物车结算,依次显示用户购物车里面的商品,数量及单价,若充值的钱数不足,则让用户删除某商品,直至可以购买,若充值的钱数充足,则可以直接购买。
    6. 用户输入Q或者q退出程序。
    7. 退出程序之后,依次显示用户购买的商品,数量,单价,以及此次共消费多少钱,账户余额多少。
    
    '''
    
    
    goods = [
        {"name" :"电脑" ,"price" :1999},
        {'name' :"鼠标" ,"price" :20}
    ]
    goods_car = {}
    while 1:
        money = input("请输入充值的钱数>>: ").strip()
        if money.isdigit():
            money = int(money)
            print('充值成功%s元' %money)
            break
        else:
            print("输入量非法字符,重新输入>>: ")
    flag = True
    while flag:
        print('商品信息如下:')
        for index, commodity_dict in enumerate(goods):
            print('{}	{}	{}'.format(index + 1, commodity_dict['name'], commodity_dict['price']))
        print('输入Q或q进行结算')
        select_num = input('请输入你的选择: ').strip()
        if select_num.isdigit():
            select_num = int(select_num)
            if 0 < select_num <= len(goods):
                if (select_num - 1) not in goods_car:
                    goods_car[select_num - 1] = {'name': goods[select_num - 1]['name'],
                                                 'price': goods[select_num - 1]['price'], 'amount': 1}
                else:
                    goods_car[select_num - 1]['amount'] += 1
                print('你选择的商品信息:商品名称: {} , 商品价格: {}  商品数量:1,  并成功添加到购物车中'.format(goods[select_num - 1]['name'],
                                                                                 goods[select_num - 1]['price']))
            else:
                print('你输入的序号超出范围,请重新输入:')
        elif select_num.upper() == 'N':
            while True:
                print('你的购物车商品如下:')
                total_price = 0
                for ind, com_dict in goods_car.items():
                    print('序号: {}商品名称 {} 商品单价 {} 此商品总价:{}'.format(ind + 1, com_dict['name'], com_dict['price'],
                                                                  com_dict['price'] * com_dict['amount']))
                    total_price += com_dict['price'] * com_dict['amount']
                print('-------> 总价: %s元' % total_price)
                if money >= total_price:
                    money = int(money)
                    print('你成功购物以上所有物品,当前余额为%s元' % money)
                    flag = False
                    break
                else:
                    print('余额不足,还差%s元,请减掉一些商品' % (total_price - money))
                    del_num = input('请输入要删除商品的序号:').strip()
                    if del_num.isdigit():
                        del_num = int(del_num)
                        if (del_num - 1) in goods_car:
                            goods_car[del_num - 1]['amount'] -= 1
                            if not goods_car[del_num - 1]['amount']:
                                del goods_car[del_num - 1]
                        else:
                            print('你输入的选项超出范围,请重新输入:')
                    else:
                        print('你输入了非法字符,请重新输入:')
        elif select_num.upper() == 'Q':
            print('下次再来')
            break
        else:
            print('你输入的选项不存在,请重新输入:')





    '''
    作业:用函数完成登录注册以及购物车的功能。
        1,启动程序,用户可选择四个选项:登录,注册,购物,退出。
        2,用户注册,用户名不能重复,注册成功之后,用户名密码记录到文件中。
        3,用户登录,用户名密码从文件中读取,进行三次验证,验证不成功则退出整个程序。
        4,用户登录成功之后才能选择购物功能进行购物,购物功能(就是将购物车封装到购物的函数中)。
        5,退出则是退出整个程序。
    '''
    
    # 定义商品信息
    shoping = {'1': {'name': '电脑', 'price': 1999},  # 选择商品编号的时候,输入的是字符串,所以此处编号用str型
               '2': {'name': '鼠标', 'price': 10},
               '3': {'name': '键盘', 'price': 20},
               }
    # 定义购物车信息
    my_car = {
        'accounts_money': 0,  # 账户余额
        'shopping_cart': {},  # 购物车内的商品,因为商品有多种,每种商品有价格和名称,所以用dic型
    }
    
    
    # 注册
    def register():
        while 1:
            username = input('请输入用户名:')
            password = input('请输入密码:')
            with open('/Users/chensihan/Documents/shanshan/作业/register_file.txt', encoding='utf-8', mode='r+') as f:
                for content in f:
                    content1 = content.split()
                    if username == content1[0]:
                        print('用户名已存在,请重新输入')
                        break
                else:
                    f.write(username + ' ' + password + '
    ')
                    print('注册成功')
                    break
    
    
    # 登录
    def login():
        global success
        count = 1
        while count <= 3:
            username = input('请输入用户名:')
            password = input('请输入密码:')
            with open('/Users/chensihan/Documents/shanshan/作业/register_file.txt', 'r', encoding='utf-8') as f:
                for content in f:
                    content1 = content.strip().split()
                    if username == content1[0] and password == content1[1]:
                        print('登录成功!')
                        success = 2
                        break
                else:
                    print('用户名或密码错误,请重新输入,还有%s次机会' % (3 - count))
                    count += 1
                    continue
                break
    
    # 购物
    def buy():
        # 充值
        while 1:
            money = input('请先充值:').strip()  # 去除输入时的左右空格等
            if money.isdigit():  # 判断输入的金额是否是数字
                my_car['accounts_money'] = int(money)  # 将充值金额传给账户余额
                print('成功充值%s元' % money)
                break
            else:
                print('充值失败,请输入正确的金额')
        
        while 1:
            # 循环打印购物车商品信息,共用户选择添加到购物车
            for i in shoping:
                print(i, shoping[i]['name'], shoping[i]['price'])
            
            num = input('请输入商品序号,将会添加至购物车,退出请输入Q/q,结算请输入n:')
            if num in shoping:  # 判断输入的商品序号是否在商品信息内
                # 记录购物车物品数量
                count = my_car['shopping_cart'].setdefault(num, 0)  # setdefault表示新建一个键值对(x, 0),并将value的值会返给count
                my_car['shopping_cart'][num] = count + 1  # 用户每次输入商品序号,购物车中该商品的数量+1
            
            # 购物车结算
            elif num.lower() == 'n':
                # 先计算出当前购物车的总金额,以便判断结算时是否充足
                total_money = 0  # 初始化购物车的总金额
                for i in my_car['shopping_cart']:
                    # 计算购物车内商品的总金额,每循环一次商品,金额都会在原来的基础上累加
                    total_money += shoping[i]['price'] * my_car['shopping_cart'][i]  # 总金额 = 商品单价*商品数量
                
                # 判断购物车中的金额是否超出当前账户余额
                if total_money > my_car['accounts_money']:  # 如果账户余额>购物车中的总金额
                    for i in my_car['shopping_cart']:  # 判断哪些商品在购物车中
                        # 打印购物车商品信息,序号、商品名称、商品单价、商品数量,供用户删除
                        print(i, shoping[i]['name'], shoping[i]['price'], my_car['shopping_cart'][i])
                    del_num = input('余额不足,请删除购物车任意商品:')
                    
                    # 判断要删除的商品是否在购物车内
                    if del_num in my_car['shopping_cart']:
                        my_car['shopping_cart'][del_num] -= 1  # 购物车内输入的编号对应的商品数量-1
                        
                        # 如果购物车内该商品只剩下一件,则直接删除该商品
                        if my_car['shopping_cart'][del_num] == 0:
                            my_car['shopping_cart'].pop(del_num)
                
                else:  # 如果账户余额<=购物车中的总金额
                    print('购物车商品如下:')
                    # 打印当前购物车剩余商品信息,商品名称、商品单价、商品数量
                    for i in my_car['shopping_cart']:
                        print(shoping[i]['name'], shoping[i]['price'], my_car['shopping_cart'][i])
                    # 购物完成后,计算当前账户余额
                    my_car['accounts_money'] -= total_money
                    print('本次共消费%s元,账户余额%s元' % (total_money, my_car['accounts_money']))
                    break
            elif num.upper() == 'Q':
                print('您已退出购物车')
                break
            else:
                print('输入错误,请重新输入')
    
    
    # 退出程序
    def tui():
        exit("您已退出程序,byebye!!!")
    
    
    # 主体结构
    dic = {
        '1': register,
        '2': login,
        '3': buy,
        '4': tui
    }
    
    
    # 开始启动并选择
    def start():
        while 1:
            print('''
                1.注册
                2.登陆
                3.购物
                4.退出
                ''')
            choice = input('>>>').strip()
            if choice in dic:
                dic[choice]()
            else:
                print('输入错误,请重新选择')
    start()











  • 相关阅读:
    《Unity3D-设置子弹发射的代码》
    《Unity3D-控制角色受伤的时候身体颜色变化的代码》
    《Unity3D-鼠标控制游戏人物的方向的代码》
    C++基础学习笔记001
    C++学习笔记
    JSON中使用jsonmapper解析的代码和步骤 学习笔记
    JSON学习笔记
    FileInfo文件的一些操作代码
    UDPClient的服务端和客户端的通信代码
    TCPListener和TCPClient之间的通信代码
  • 原文地址:https://www.cnblogs.com/caoyinshan/p/12119530.html
Copyright © 2020-2023  润新知