功能:
自定义工资水平,可选商品加购
余额实时提醒
用到的知识点:
列表、if多分支、循环、高亮输出
未解决bug
删除商品后不能自动退出
代码如下:
if shopping_list: shopping_list.pop(user_choice) print("已删除") else: print("你没有购买任何商品") del_list=0 #此处del_list为循环标志位 break
完整代码如下:
1 product_list = [ (‘Iphone‘,5800), 2 (‘荣耀Watch‘,999), 3 (‘honorV20‘,2399), 4 (‘Iphone10‘,10000),] 5 shopping_list = [] 6 salary = input("Input your salary:") 7 if salary.isdigit():#isdigit方法判断字符串是否只由数字组成 8 salary = int(salary) 9 print("你可以购买如下商品:") 10 while True: 11 for index,item in enumerate(product_list): 12 # print(product_list.index(item),item) 13 print(index+1,item)#将序号调整为1234 14 user_choice = input( 15 ‘‘‘选择要买什么? 16 输入商品序号选择商品、‘index‘查看购物车、‘del‘开始删除所选商品、‘del all‘清空购物车、输入‘q‘退出! 17 --->‘‘‘) 18 if user_choice.isdigit(): 19 user_choice = int(user_choice) 20 user_choice-=1#对应减一保证序列对应所选商品 21 if user_choice <len(product_list) and user_choice>=0: 22 # 将选择的商品序号记录并进行相应判断处理 23 p_item = product_list[user_choice] 24 if p_item[1] <=salary: 25 shopping_list.append(p_item)#添加购物车清单 26 salary -= p_item[1]#工资消耗 27 print( 28 ‘‘‘Added %s into shopping cart,余额: \033[31;1m%s\033[0m 29 ‘‘‘%(p_item,salary)) 30 else: 31 print("\033钱好像不够了,还剩[%s]\033[0m" % salary) 32 else: 33 print("商品 [%s] 不存在!"% user_choice) 34 elif user_choice == ‘index‘: 35 print("已经加购的商品:") 36 for p in shopping_list: 37 print(p) 38 print("-*-*-*-*-*-*-*-*") 39 print("开始选择商品:") 40 elif user_choice == ‘q‘: 41 print("-------shopping list--------") 42 if len(shopping_list)==0: 43 print("购物车空空如也!") 44 for p in shopping_list: 45 print(p) 46 print("你的余额为:",salary) 47 exit() 48 elif user_choice == ‘del‘: 49 for index, item in enumerate(shopping_list): 50 # print(product_list.index(item),item) 51 print(index + 1, item) # 将序号调整为1234 52 del_list=1 53 while del_list: 54 user_choice=input("删除哪个?") 55 if user_choice.isdigit(): 56 user_choice = int(user_choice) 57 user_choice -= 1 # 对应减一保证序列对应所选商品 58 if user_choice < len(shopping_list) and user_choice >= 0: 59 if shopping_list: 60 shopping_list.pop(user_choice) 61 print("已删除") 62 else: 63 print("你没有购买任何商品") 64 del_list=0 65 break 66 elif user_choice == ‘del all‘: 67 del shopping_list 68 print("开始重新选择商品") 69 elif user_choice == ‘q‘: 70 print("开始选择商品") 71 del_list=0 72 else: 73 print("对不起,没有该选项!") 74 else: 75 print("对不起,没有该选项!")