购物车小程序(while循环,列表)
1 while True: 2 salary = input("please input your salary:") 3 if salary.isdigit(): 4 salary=int (salary) 5 break 6 else: 7 print("Invalid input! please input a number:") 8 9 product_cart = [['iphone6s',5800], #定义商品列表 10 ['macbook',9000], 11 ['coffee',30], 12 ['python book',80], 13 ['bicycle',1500] 14 ] 15 shopping_cart = [] #定义购物车 16 balance=salary 17 18 while True: 19 for i,v in enumerate(product_cart,1): #enumerate参数将商品列表循环打印,并且第一行从1开始 加上序号 20 print(i,v) 21 22 choise = input("please input your selection[typing 'q' to quit]:") 23 if choise.isdigit(): #判断是否是数字 24 choise=int(choise) 25 if choise >=1 and choise<=len(product_cart): #判断输入的字符是否符合商品列表所在的范围 26 sales =product_cart[choise-1] #将用户选择的商品赋值给sales 27 if balance >=sales[1]: #判断余额是否足够购买该商品 28 balance -=sales[1] #购买完后将余额减去商品价格 29 shopping_cart.append(sales) #将商品加入购物车 30 print("your balance is %s :"%balance) 31 print() 32 else: 33 print("your balance is %s,not enough to buy this one,please try another products!"%balance,) 34 print() 35 36 37 else: 38 print("no such a selection") 39 elif choise == 'q': #判断是否是q选择退出 40 print("your shopping cart is:") 41 for i, v in enumerate(shopping_cart, 1): 42 print(i, v) 43 break 44 else: 45 print("Invalid typing.please typing a number!") #非数字执行的操作