购物车(2)优化代码

优化,更改为使用列表

# -*- coding: utf-8 -*-
# @Author: oppend
# @Date:   2017-07-27 19:43:59
# @Last Modified by:   oppend
# @Last Modified time: 2017-07-27 23:08:16
product_list = [('bike',1500),('tea',80),('computer',3500),('book',130)]
my_amount = input('您的资金(元):')
shopping_car = {}
shopcar = shopping_car.keys()
while True:
    print('>>>>>>>>>>>>商品列表<<<<<<<<<<<')
    for num,product in enumerate(product_list,1):
        print('[',num,']','=>','{0:<10}{1:>12}'.format(product[0],product[1]))
    print('-------------end---------------')

    choice = input('输入购买商品序号[q:退出]:')
    # 序号输入是否为数字
    if choice.isdigit():
        choice = int(choice)-1
        my_amount = int(my_amount)
        # 序号选择是否超出范围
        if 0 <= choice < len(product_list):
            choice_product = product_list[choice]
            product_name = str(choice_product[0])
            product_price = int(choice_product[1])
            # 金额是否足够
            if my_amount >= product_price:
                # 购物车是否存在商品
                if product_name not in shopcar:
                    shopping_car[product_name] = [product_price,1]
                else:
                    total = shopping_car[product_name][0] * 2
                    count = shopping_car[product_name][1] + 1
                    shopping_car[product_name] = [total,count]
                # 计算余额
                balane = my_amount - product_price
                print('购买了{0}x1,剩余金额{1}'.format(product_name,balane))
                my_amount = balane
            else:
                print('余额不足!')
                continue
        else:
            print('商品序号[{0}]不存在!'.format(choice+1))
            continue
    elif choice.lower() == 'q':
        if len(shopping_car) > 0:
            print('==========您已购买=========')
            for name in shopcar:
                price = shopping_car[name][0]
                product_num = shopping_car[name][1]
                print('{0:<10}{1:<15}x{2}'.format(name,price,product_num))
            print('===========================')
            break
    else:
        print('商品序号[{0}]错误!'.format(choice))
        continue
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值