'''
程序练习
购物车程序
需求:
1、启动程序后,让用户输入工资,然后打印尚品列表
2、允许用户更加尚品编号购买商品
3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
4、可随时退出,退出时,打印已经购买的商品和余额
'''
product_list = [
('iphone',5800),
('mac pro',9800),
('bike',800),
('watch', 10600),
('coffee', 31),
('alex python', 120)
]
shopping_list = []
salary = input('input your salary:') #输入工资
if salary.isdigit(): #判断工资是否是数字
salary = int(salary) #如果是数字给他int
while True:
for index,item in enumerate(product_list): #打印商品列表(enumerate的意思是把下标取出来)
#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(product_list) and user_choice >=0: #判断用户商品编号
p_item = product_list[user_choice] #通过下标把商品取出来
if p_item[1] <= salary: #买的起
shopping_list.append(p_item) #添加到商品list里面
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')
Python学习之购物车程序练习
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.