購物車程序:python
需求:git
1.啓動程序後,讓用戶輸入工資,而後打印商品列表app
2.容許用戶根據商品編號購買商品iphone
3.用戶選擇商品後,監測餘額是否夠,夠就直接扣款,不夠就提醒ide
4.可隨時退出,退出時,打印已購買商品和餘額spa
#!/usr/bin/env python # -*- coding:utf-8 -*- shopping_list = [] # 購物車 product_list = [ # 商品清單 ('iphone', 5800), ('mac pro', 9800), ('bike', 800), ('watch', 10600), ('coffee', 31), ('xcn python', 120), ] salary = input("你的工資是多少:") if salary.isdigit(): # 判斷輸入是否爲數字 salary = int(salary) while True: for index, item in enumerate(product_list): # 現實下標(index)根據下標購買物品 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) salary -= p_item[1] print("購買的物品:%s,餘額:%s" % (p_item, salary)) else: print("餘額不足") elif user_choice == 'q': print("----------shopping list------------") for p in shopping_list: print(p) print("如今餘額:", salary) exit("歡迎下次光臨") else: print("很差意思,商品已下架!")
註釋:ip
len(product_list) #表示product_list下標最大值