购物车

功能要求:

  • 要求用户输入总资产,例如:2000
  • 显示商品列表,让用户根据序号选择商品,加入购物车
  • 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
  • 附加:可充值、某商品移除购物
  • goods = [
        {"name": "电脑", "price": 1999},
        {"name": "鼠标", "price": 10},
        {"name": "游艇", "price": 20},
        {"name": "美女", "price": 998},
    ]
  • goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998},
    ]
    shopping_cart = []
    your_asset = int(input('请输入你的总资产: '))
    for my_goods in enumerate(goods):
        index = my_goods[0]#选择商品的序号
        shopping_list = my_goods[1]#表示选择商品的清单
        shopping_name = shopping_list['name']#表示选择的商品的名字
        shopping_price = shopping_list['price']
        print(shopping_list,(index,shopping_name,shopping_price))
    while True:
        your_choose = input('请输入你想要购买商品的序号: ').strip()
        if  your_choose.isdigit():
            your_choose = int(your_choose)
        else:
            print('输入错误,请重新输入')
            continue
        if your_choose < len(goods) and your_choose >= 0:
            my_index = goods[your_choose]
            my_shopping_name = my_index['name']
            my_shopping_price = my_index['price']
        else:
            print('输入错误,请重新输入')
            continue
        if int(my_shopping_price) < int(your_asset):
            shopping_cart.append(my_shopping_name)
            print(shopping_cart)
            your_asset = your_asset - my_shopping_price
            print('你的剩余的金额为%s'%(your_asset))
            go_buy = input('是否想继续购买??>>请回答yes或者no: ')
            if go_buy == 'yes':
                print('请继续买你心仪的商品吧!')
            else:
                for i in shopping_cart:
                    print('你购买的商品是:%s'%(i))
                break
        else:
            print('你的余额不足!!')
            shopping_cart.append(my_shopping_name)
            ans = input('是否要继续充值>>请回答yes或者no: ')
            if ans == 'yes'.strip():
                recharge = input('请输入你所要充值的金额').strip()
                recharge = int(recharge)
                your_asset = your_asset + recharge
                print('您充值后的金额为%s'%(your_asset))
            elif ans == 'no'.strip():
                print('余额不足')
                remove_shopping_cart = input('是否要将商品移除购物车>>请回答yes或者no: ')
                if remove_shopping_cart == 'yes':
                    remove_shopping = input('请输入要移除的商品序号: ').strip()
                    shopping_cart.remove(goods[int(remove_shopping)]['name'])
                    print('您的购物列表如下: ')
                    for j in shopping_cart:
                        print(j)
                    break
                elif ans == 'no':
                    print('购买失败')
                    break
原文地址:https://www.cnblogs.com/huangxiaohan/p/7778459.html