程序练习
程序:购物车程序
需求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
1 # -*- coding:utf-8 -*- 2 # !/usr/bin/env python 3 # Author:dc 4 5 list_of_product = [["IphoneX", 8999], ["Apple Air", 3088], ["MacBook Air", 5999], ["MacBookPro", 128000], 6 ["Iphone6", 4999]] 7 list_of_shopping = [] 8 money_of_guest = input("请输入您的预存款:") 9 if money_of_guest.isdigit(): 10 money_of_guest = int(money_of_guest) 11 while True: 12 13 print("\n商店产品列表如下\n") 14 15 for l in list_of_product: 16 print(list_of_product.index(l), l) 17 18 num_product = input("请输入您需要购买商品的序号:") 19 20 if num_product.isdigit(): 21 num_product = int(num_product) 22 23 if money_of_guest < list_of_product[num_product][1]: 24 print("您的余额不足以购买此商品,请选择其他商品或输入q退出") 25 else: 26 print("已将{name_of_product}加入您的购物车".format(name_of_product=list_of_product[num_product][0])) 27 money_of_guest = money_of_guest - list_of_product[num_product][1] 28 print("您的余额还有{b}".format(b=money_of_guest), "元") 29 list_of_shopping.append(list_of_product[num_product]) 30 elif num_product == "q": 31 print("\n您的购物清单如下:\n") 32 for i in list_of_shopping: 33 print(i) 34 print("您的余额还有{b}".format(b=money_of_guest), "元,欢迎下次再来!") 35 exit() 36 else: 37 print("请输入正确的金额")