需求:
启动程序后,让用户输入工资,然后打印商品列表
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时,打印已购买商品和余额
我的博客
启动程序后,让用户输入工资,然后打印商品列表
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时,打印已购买商品和余额
#Author:liubin
goods_list=[('iphone',5000),
('clothing',1000),
('book',100),
('coffee',50),
('tea',200),
]
shopping_list = []
salary = input("Input your salary:")
if salary.isdigit(): #Python isdigit() 方法检测字符串是否只由数字组成。
salary = int(salary) #如果工资是数字,使用int
while True:
for index,item in enumerate(goods_list): #http://www.runoob.com/python/python-func-enumerate.html一句话就是把下标取出来
#print(product_list.index(item),item)
print(index,item) #打印商品列表
user_choice = input("选择要买嘛?>>>:")
if user_choice.isdigit():
user_choice = int(user_choice)
if user_choice < len(goods_list) and user_choice >=0:
p_item = goods_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[41;1m你的余额只剩[%s]\033[0m" % salary)
else:
print("product code [%s] is not exist!"% user_choice)
elif user_choice == 'q':
print("--------shopping list------")
for p in shopping_list:
print(p)
print("Your current balance:",salary)
exit()
else:
print("Invalid option")