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('请正确输入你的资金数')

 

二.以元组放在列表中的形式存货品信息:

 

#/user/bin/env python
# -*- coding:utf-8 -*-

#一一对应不可取
#productlist=[]
#price_list=[]

product_list=[
('Iphone',5800),
('Mac Pro',9800),
('Bike',800),
('Coffee',31),
('Alex Python',120)
]
shopping_list=[]
salary=input('Input your salary:\n')
if salary.isdigit():#isdigit判断是数字但是是str类型的值
salary=int(salary)
while True:
for index,item in enumerate(product_list):
#print(product_list.index(item),item)
print(index,item)
User_choice=input('选择买的产品:\n')
if User_choice.isdigit():
User_choice=int(User_choice)
if User_choice<len(product_list) and User_choice>=0:
p_item=product_list[User_choice]
if p_item[1]<=salary:#买得起
shopping_list.append(p_item)
salary-=p_item[1]
print('Added %s into shopping cart, your current balance is \033[31;1m%s\033[0m'%(p_item,salary))
else:
print('\033[31;1m你的余额只剩[%s]\033[0m'%(salary))
else:
print('选择不存在')
elif User_choice=='q':
print('----shopping list----')
for p in shopping_list:
print(p)
print('Your balance:\n',salary)
exit()
else:
print('invalid option')
else:
print('请正确输入你的资金数')

 

posted @ 2019-07-18 17:06  MarkL9527  阅读(339)  评论(0编辑  收藏  举报