实例需求:
1. 启动程序后,让用户输入工资,然后打印商品列表;
2. 允许用户根据商品编号选购商品;
3. 用户选择商品后,程序自动判断所剩余额是否足够?足够就扣款并加入购物清单,不够就提示;
4. 程序可以随时退出,退出时,打印已经购买的商品和所剩余额。
1 #!/usr/local/bin/python3 2 # Author:Jonas Mao 3 4 product_list = [ 5 ('IphoneX',7800), 6 ('Mac Pro',12800), 7 ('Bicycle',1800), 8 ('Coffee',38), 9 ('IWatch',3800), 10 ('Python',88), 11 ] 12 13 shopping_list = [] 14 salary = input("Input Salary >>>:").strip() 15 if salary.isdigit(): 16 salary = int(salary) 17 while True: 18 for index,item in enumerate(product_list): 19 print(index,item) 20 user_choice = input("Take It Home >>>:").strip() 21 if user_choice.isdigit(): 22 user_choice = int((user_choice)) 23 if user_choice < len(product_list) and user_choice >= 0: 24 p_item = product_list[user_choice] 25 if p_item[1] <= salary: 26 shopping_list.append(p_item) 27 salary -= p_item[1] 28 print("Added %s into List, Current Balance is \033[31;1m%s\033[0m" %(p_item,salary) ) 29 else: 30 print("\033[41;1mSorry,[%s] iIs not enough!\033[0m" % salary) 31 else: 32 print("Product index [%s] is not exist!" % user_choice) 33 elif user_choice == 'q': 34 print('Shopping List'.center(30,'-')) 35 for p in shopping_list: 36 print(p) 37 print("\033[31;1mCurrent Balance: %s\033[0m" %(salary)) 38 exit() 39 else: 40 print("Sorry,Invalid Option!") 41 else: 42 print('Sorry, Your salary is not a digit!')