您的位置:首页 > 编程语言 > Python开发

python练习:购物车

2016-11-12 22:09 211 查看
第一次写(没用列表)

def Status(price1,status1,sumall):
if status1 == 1:
sumall = AddPrice(price1,sumall)
return sumall
if status1 == 0:
sumall = MinusPrice(price1,sumall)
return sumall

def AddPrice(price1,a,sumall):
sumall = sumall + price1
return sumall

def MinusPrice(price1,sumall):
sumall = sumall - price1
return sumall
######################################################
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
money1 = int(input("请您输入您的总资产:"))
sumall = 0
status1 = 1
while 1:
while 2:
for n in range(len(goods)):
print("商品序号"+ str(n+1) + ":"+goods
['name'] + str(goods
['price']) + "元")
a = int(input("请输入您想购买的商品序号:")-1)
sumall = Status(goods[a]['price'],status1,sumall)
if sumall > money1:
status1 = 0
sumall = Status(goods[a]['price'],status1,sumall)
print("您的资产不够,请重新输入")
continue
else:
break

sfjs = input("结算请按'0'',修改购物车请按'1'':")
if sfjs == 0:
syje = money1 - sumall
print("购买成功,您还剩"+str(syje))
break
else :
xiugai = input("继续购买请按'1'',删除物品请按'0'':")
if xiugai == 0:
status1=0
continue
else:
status1 ==1
continue


第二次优化(使用列表字典)

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# # python 2.7.0

def Jgzh ():
Sum = 0
for i in range(0,len(xglist)):
Sum = Sum + xglist[i]['price']
# Sum = int(Sum)
return Sum
def GwcList(Geta,GetStatus):
if GetStatus == 1:
xgdic['price'] = goods[a]['price']
xgdic['name'] = goods[a]['name']
xglist.append(xgdic)
if GetStatus == 0:
del xglist[a]
xglist=[]
xgdic={}
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
Money = int(input("请您输入您的总资产:"))
while 1:
while 2:
for n in range(len(goods)):
print("商品序号"+ str(n+1) + ":"+goods
['name'] + str(goods
['price']) + "元")
a = int(input("请输入您想购买的商品序号:")-1)
Status = 1
GwcList(a,Status)
Sum = Jgzh()
if Sum > Money:
Status = 0
GwcList(-1,Status)
Sum = Jgzh()
print("您的资产不够,请重新输入")
continue
else:
break
while 3:
Sfjs = input("结算请按'0'',修改购物车请按'1'':")
if Sfjs == 0:
Syje = Money - Jgzh()
print("购买成功,共计花费:"+str(Jgzh())+"元,还剩余额:"+str(Syje)+"元,详细购买清单如下:")
for i in range(0,len(xglist)):
print(str(i+1) + "、" + xglist[i]['name'] + str(xglist[i]['price']) +"元")
break
else :
XiuGai = input("删除物品请按'0',继续购买请按'1':")
if XiuGai == 0:
Status = 0
for n in range(len(xglist)):
print("商品序号"+ str(n+1) + ":"+xglist
['name'] + str(xglist
['price']) + "元")
a = int(input("请输入您想删除的商品序号:")-1)
GwcList(a,Status)
continue
else:
Status == 1
break
if Sfjs == 0:
break
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: