Python购物车的两种写法
需求:
1.输入funds,给出货品列表
循环进行选择
2.根据货品编号进行选择
3.加入购物车
4.退出系统,输出余额
一.直接用列表形式存详细货品信息,进行数据处理:
#!/user/bin/env python
# -*- coding:utf-8 -*-
Goodslist=\
[
'1 Iphone 5800',
'2 Huawei 4699',
'3 LuckinCoffee 27',
'4 Alex Python 81',
'5 Niu E-bicycle 1580'
]
#print('Please input your shopping funds:\n')
Funds = input('Please input your shopping funds:\n', )
Bought_List=[]
'''
print(Goodslist)
import re
price = re.findall(r'\d+\.?\d', Goodslist[1])
print(type(price))
Goodsprice=price[0]
print(type(Goodslist))
#print(Goodslist[Num-1])
#print(Goodsname)
'''
if Funds.isdigit():
Funds=int(Funds)
while True:
print('If you input "q", you will qiut the system!')
Num = input('Select your goods_num:\n')
if Num.isdigit():
Num=int(Num)
if Num<len(Goodslist)+1 and Num>=0:
import re
price= re.findall(r'\d+\.?\d', Goodslist[int(Num)-1])
Goodsprice=price[0]
#print(re.findall(r'\d+\.?\d',Goodslist[int(Num)-1]))
#print(price[0])
#print(price[0])
#print(Goodslist[Num - 1].replace(' ', ''))
Goodsname = ''.join(re.findall(r'[A-Za-z]', Goodslist[int(Num) - 1].replace(' ', '')))
Goodsname1=Goodsname[0]
Goodsinfo = []
if Funds>=int(Goodsprice):#买得起
Funds -= int(Goodsprice)
Goodsinfo.append(Goodsname1)
Goodsinfo.append(Goodsprice)
Bought_List.append(Goodsinfo)
print('Added %s to your shopping cart!, your balance is \033[31;1m%s\033[0m'%(Goodsname1,Funds))
else:
print('\033[31;1mYour balance is[%s]\033[0m' % (Funds))
else:
print('Nonexistent item')
elif Num=='q':
print('----shopping list----')
for p in Bought_List:
print(p)
print('Your balance:',Funds)
exit()
else:
print('invalid option')
else:
print