要求实现:
1.程序开始运行时要求手动填入工资金额
2.然后展示一份带有价格的商品列表
3.选择某个商品,足够金额购买就添加到购物车,否则提示无法购买
4.退出后列出购物车清单
#!/usr/bin/python
# -*- coding:utf-8 -*-
# Author: Jacket
#定义商品列表
product_list = [
('macair',8000),
('iphone',3000),
('xiaomi',1000),
('mobike',800),
('coffee',50),
]
#购物车默认为空
shopping_list = []
salary = input("input your salary:")
if salary.isdigit(): #判断输入的工资金额是否为数字
salary = int(salary) #转化为整型数据
while True:
for index,item in enumerate(product_list):
print(index,item) #展示商品列表
user_choice = input("你要买啥:")
if user_choice.isdigit():
user_choice = int(user_choice)
if user_choice < len(product_list) and user_choice >= 0: #判断用户输入的id是否在商品列表长度范围内
p_item = product_list[user_choice] #将用户输入的id作为商品列表的索引,定位用户选择的商品信息
if p_item[1] <= salary: #商品价格小于或等于余额
shopping_list.append(p_item) #添加此商品到购物车
salary -= p_item[1] #剩余工资 = 减去商品价格后的余额
#print("你购买的商品是%s,剩余的余额是%s" % (shopping_list,salary))
print("add %s to your shopping cart succee,and your salary is %s" % (p_item[0],salary))
else:
print("你的余额%s不足,无法购买商品" %salary)
else:
print("你选择的商品不存在")
elif user_choice == 'q':
print("-------购物车清单-------")
for i in shopping_list:
print(i)
exit()
else:
print("格式不正确,请输入数字或者q...")
else:
print("你输入的余额[%s]格式不正确" % salary)