为练习使用字典相关指令,写了此购物车脚本。

可实现功能:商品列表显示、选择购物、添加购物车、显示购物车商品、删除购物车商品等。购物过程可进一步优化。

此脚本使用面向过程的编程方式,可使用函数式编程进一步优化。

# #! usr/bin/env python
# # -*- coding:utf-8 -*-
#2017.4.6 by wang
#the frist edition by pyCharm
#完成购物车功能代码,实现商品挑选、购买、充值等功能。

#自定义函数区
#   显示商品列表
def show_goods(goods):
    print('商品及价钱:')
    for i in goods:
        print('{}:{}元'.format(i['name'],i['price']))

#购物车功能实现区
#   用户输入当前账户总资产
asset = 0
asset = int(input('当前账户总资产(元): '))
#   显示商品列表
goods = [
    {'name': '服装', 'price': 55},
    {'name': '食品', 'price': 30},
    {'name': '图书', 'price': 20},
    {'name': '用品', 'price': 80}
]
show_goods(goods)
#   请用户选择商品
shoppingCart = {}
while True:
#   用户选择需要购买的商品
    want2Buy = input('请选择需要购买的商品名称: ')
#   将用户选择的商品加入购物车
    for i in goods:
        if i['name'] == want2Buy:
            if want2Buy in shoppingCart.keys():
                shoppingCart[want2Buy] ['数量']+=1
            else:
                shoppingCart[want2Buy]={'单价(元)':i['price'],'数量':1}
            break
        else:
            continue

#   继续选择或购买
    continueBuy = input('继续挑选:1   去购物车:其它 \n>>>')
    if continueBuy == '1':
        continue
    else:
        break

#   显示购物车信息
for i,j in shoppingCart.items():
    print('{}:{}'.format(i,j))

#   显示合计购物车商品总价
totalPrice = 0
for j in shoppingCart.values():
    totalPrice+=j['单价(元)']*j['数量']
print('购买商品总计{}元'.format(totalPrice))


#若资产总额大于商品总价,完成购买,否则提示余额不足
if totalPrice <= asset:
    totalMoney = asset-totalPrice
    print('完成购买,余额{}元。'.format(totalMoney))
else:
    print('余额不足。')
    temp = input('充值:1  移除购物车商品:2   退出:其它\n>>>')
    if temp == '1': #充值
        money = input('账户充值(元):\t')
        asset +=money
        print('当前账户余额:{}元。'.format(asset))
    elif temp == '2':   #移除商品
        while True:
            delGoods = input('请输入需要删除的商品名称:\t')
            if delGoods in shoppingCart.keys():
                shoppingCart[delGoods]['数量']-=1
                if shoppingCart[delGoods]['数量']==0:
                    shoppingCart.pop(delGoods)
            else:
                print('输入错误,请重新输入。')
                continue
            if shoppingCart is None:
                print('购物车已空!')
                break
            else:
                  for i, j in shoppingCart.items():
                      print('购物车内物品如下:')
                      print('{}:{}'.format(i, j))
                  temp = input('继续删除商品:1  退出:其它\n>>>')
                  if temp=='1':
                     continue
                  else:
                      break
    else:
        print('已退出。')