python学习:购物车程序

购物车程序

product_list = [
('mac',9000),
('kindle',800),
('tesla',900000),
('python book',105),
('bike',2000),
]
saving = input('please input your money:')
shopping_car = []
if saving.isdigit(): #验证输入的是否为数字格式,如果成立则继续
saving = int(saving)
while True:
#打印商品内容
# for i in product_list:
# print(product_list.index(i),i)
# for i in enumerate(product_list,1):
# print(i)
for i,v in enumerate(product_list,1):
print(i,v) #print(i,'>>>>',v)
choice = input('选择购买商品编号[退出:q]:') #引导用户选择商品
if choice.isdigit():
choice = int(choice) #验证输入是否合法
#len(product_list) 得到列表长度
if choice > 0 and choice <= len(product_list):
p_item = product_list[choice-1] #将用户选择商品通过choice取出来
if p_item[1] < saving:
saving -= p_item[1]
shopping_car.append(p_item) #如果钱够,用saving本金减去该商品价格,并将该商品加入购物车
else:
print('余额不足,还剩%s'%saving)
print(p_item)
else:
print('编码不存在')
elif choice == 'q':
print('--------------您以及购买如下商品--------------')
for i in shopping_car:
print(i) #循环遍历购物车内的商品,购物车存放的是已购商品
print('您还剩%s元钱'%saving)
break
else:
print('invalid input')

猜你喜欢

转载自www.cnblogs.com/pl-2018/p/9465480.html
今日推荐