购物车代码

goods=[{"name":	"电脑",	"price":	1999},
 {"name":	"鼠标",	"price":	10},
 {"name":	"游艇",	"price":	20},
 {"name":	"美女",	"price":	998},]
shopcart=[]
ii=1
price=0

for i in goods:
    print(ii,i['name'],i['price'])
    ii+=1
money=int(input('你拥有的总资产:'))
while True:
    n=input('你想购买的商品序号:(结账请按q,删除购物车请按b,查看购物车请按c)').strip()
    if n=='q':
        break
    if n=='c':
        print('已选购商品:')
        for i in shopcart:
            print('商品名称:',i['name'],'商品单价:',i['price'])
        continue
    if n=='b':
        print('购物车已有:')
        ib=1
        for i in shopcart:
            print(ib,i['name'],i['price'])
            ib+=1
        while True:
            nb=input('请输入想删除的物品序号:(选择完输入d:)')
            if nb.lower()=='d':
                break
            if int(nb)>len(shopcart) or int(nb)<=0:
                print('请输入合法数字!')
                continue
            del shopcart[int(nb)-1]
            print('购物车还有商品:')
            ib=1
            for i in shopcart:
                print(ib,i['name'],i['price'])
                ib+=1
        continue
    if not n.isdecimal():
        print('请输入十进制数字!')
        continue
    if int(n)<1 or int(n)>4:
        print('请输入合法序号:')
        continue
    shopcart.append(goods[int(n)-1])
    price=0
    for i in shopcart:
        price=price+i['price']
    print('你总资产为:%s' %money,'总花销金额为:%s' %price)
print('购物车总金额为:%s' %price)
print('你拥有的总资产:%s' %money)
if price>money:
    print('账户余额不足!请充值!')
else:
    print('恭喜!购买成功!')

  我发现if break,if continue ,比if else 好用,感觉是。不用套太多的循环

posted @ 2017-08-21 23:47  骑者赶路  阅读(288)  评论(0编辑  收藏  举报