今天学习了python写购物车的程序,受益匪浅。
1、学会了打印如何列表list。
for item in product_list:
print(item)
2、学会了一个取下标的函数。product_list.index(item)
3、学会了enumerate(a)
a=[1,2,3]
enumerate(a)
》》》for i in enumerate(a):print(i)
1 # author:zfp 2 3 product_list=[('Iphone',5800), 4 ('zfp python',88), 5 ('pen',2), 6 ('desk',380), 7 ('huawei mobiphone',2700) 8 ] 9 shopping_cart=[] 10 salary=input("Input your salary:") 11 if salary.isdigit(): 12 salary=int(salary) 13 while True: 14 #for item in product_list: 15 #print(product_list.index(item),item) 16 for index,item in enumerate(product_list): 17 print(index,item) 18 user_choice=input("选择要买什么?>>>:") 19 if user_choice.isdigit(): 20 user_choice=int(user_choice) 21 if user_choice<len(product_list) and user_choice>=0: 22 p_item=product_list[user_choice] 23 if p_item[1]<=salary:#买的起 24 shopping_cart.append(p_item) 25 salary-=p_item[1] 26 print("Added %s into shopping cart,your current salary is %s"%(p_item,salary)) 27 else: 28 print("你的余额不够哦,只有%s还买个卵呀" % salary) 29 else: 30 print("product code [%s] is not exist!"% user_choice) 31 elif user_choice=='q': 32 print("-------shopping list ---------") 33 for p in shopping_cart: 34 print(p) 35 print("Your current balance:",salary) 36 exit() 37 else: 38 print("Invalid option")