要求实现功能:
启动程序后,用户输入工资,然后打印商品列表
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时, 打印已购买商品和余额
product_list = [ ('iphone', 8100),
('mac pro', 13000),
('sea food', 600),
('bed', 3200),
('chair', 123),
('blue tooth header', 1800)
]
shopping_list = []
salary = input("please input your salary here: ")
if salary.isdigit(): #判断工资是不是数字
salary = int(salary) #工资是数字,把salary类型变成int
while True: #进入循环
for index, item in enumerate(product_list):
print(index, product_list)
user_choice = input("please put number to choice what you want>>>>>>:")
if user_choice.isdigit(): #判断用户输入必须是数字
user_choice = int(user_choice)
if user_choice < len(product_list) and user_choice >= 0: #用户选择的数字小于product list长度 且大于等于0
p_item = product_list[user_choice]
if p_item[1] <= salary:
shopping_list.append(p_item) #shopping list 里增加该item
salary -= p_item[1] #购买物品后在工资里扣除相应的钱
print("you have added %s into your shopping cart, and your current balance is: \033[31;1m%s\033[0m" %(p_item,salary))
# \033[31;1m%s\033[0m 字体颜色改成红色
else:
print("\033[31;1m you don't have enough salary!\033[0m")
else:
print("%s is no exist option!" %user_choice)
elif user_choice == 'q':
print("----------------your shopping list---------------")
for p in shopping_list:
print(p)
print(" your current balance is:", salary)
exit()
else:
print("invalid option")
使用 for index, item in enumerate(product_list)使 product_list更加灵活,后期可增加删除里面元素并且不影响原有代码
注: 在list打印出来的时候是这样的:(尚未解决)
0 [('iphone', 8100), ('mac pro', 13000), ('sea food', 600), ('bed', 3200), ('chair', 123), ('blue tooth header', 1800)]
1 [('iphone', 8100), ('mac pro', 13000), ('sea food', 600), ('bed', 3200), ('chair', 123), ('blue tooth header', 1800)]
2 [('iphone', 8100), ('mac pro', 13000), ('sea food', 600), ('bed', 3200), ('chair', 123), ('blue tooth header', 1800)]
3 [('iphone', 8100), ('mac pro', 13000), ('sea food', 600), ('bed', 3200), ('chair', 123), ('blue tooth header', 1800)]
4 [('iphone', 8100), ('mac pro', 13000), ('sea food', 600), ('bed', 3200), ('chair', 123), ('blue tooth header', 1800)]
5 [('iphone', 8100), ('mac pro', 13000), ('sea food', 600), ('bed', 3200), ('chair', 123), ('blue tooth header', 1800)]
但是不影响购买