练习18(购物车)

练习18

goods = [{'name':'电脑','price':1999},
         {'name':'鼠标','price':10},
         {'name':'游艇','price':20},
         {'name':'美女','price':998}
        ]
shopping_car = {}
while 1:
    money = input('请充值:').strip()
    if money.isdigit():
        money = int(money)
        break
    else:
        print('您输入的金钱有非数字的元素,请重新输入')
flag = True
while flag:
    print('+++++++商品展示+++++++')
    for index,commodity_dict in enumerate(goods):
        print('{}\t{}\t{}\t'.format(index+1,commodity_dict['name'],commodity_dict['price']))
    print('输入n或N\t 购物车结算\n输入q或Q\t 退出程序')
    print('+++++++++++++++++++++')
    select_num = input('请输入你的选择:')
    if select_num.isdigit():
        select_num = int(select_num)
        if 0 < select_num <= len(goods):
            if (select_num -1) not in shopping_car:
                shopping_car[select_num - 1] = {'name':goods[select_num - 1]['name'],
                                                'price':goods[select_num - 1]['price'],'amount':1}
            else:
                shopping_car[select_num - 1]['amount'] += 1
            print('您以成功将:商品为{} 单价为{} 数量为{}加入到购物车'
                  .format(shopping_car[select_num - 1]['name'],shopping_car[select_num - 1]['price'],shopping_car[select_num - 1]['amount']))
        else:
            print('没有此商品哦,请重新输入')
    elif select_num.upper() == 'N':
        # print(shopping_car)
        while 1:
            total_price = 0
            print('购物车商品列表如下:')
            for ind,com_dict in shopping_car.items():
                print('{} 商品名称:{} 商品单价:{} 商品数量:{}'
                      .format(ind + 1, shopping_car[ind]['name'], shopping_car[ind]['price'], shopping_car[ind]['amount']))
                total_price += shopping_car[ind]['price'] * shopping_car[ind]['amount']
            print('此次购物总价格:%s元' % total_price)

            if money < total_price:
                del_num = input('您的余额不足,请选择需要删除的商品序号(默认每次数量减一)').strip() ## 可以扩展充值功能
                if del_num.isdigit():
                    del_num = int(del_num)
                    if (del_num-1) in shopping_car:
                        shopping_car[del_num - 1]['amount'] -= 1
                        if not shopping_car[del_num - 1]['amount']:
                            shopping_car.pop(del_num-1,'无从key')
                    else:
                        print('没有此商品哦,请重新输入')
                else:
                    print('不理解您输入的是什么哦,请重新输入')
            else:
                money -= total_price
                print('您已经成功购买了上面所有商品,剩余%s元' % money)
                flag = False
                break
    elif select_num.upper() == 'Q': # 保留购物车未结算的商品 写入文件 ,以便后续再次结算
        break
    else:
        print('不理解您输入的是什么哦,请重新输入')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值