购物车程序

程序要求:

  基础版 

1、设定账户金额
2、打印商品列表 3、让用户选择商品(若账户金额足够,可无限购买,直至退出) 4、选择后的商品加入购物车 5、打印购物车清单,统计消费金额和余额

  基础版参考答案

 1 #-*- coding:utf-8 -*-
 2 # write by cc
 3 
 4 product_list = [["iphone",10000],['HuaWei',12000],['apple',6],['coffee',60],['Reader',10],['bicyle',1000],['Nike',500]]
 5 shopping_cart = [] # 购物车列表
 6 balance = int(input('请输入你的工资:¥'))
 7 cost = 0 # 消费金额
 8 exit_flag = False # 标志位(退出标志)
 9 while not exit_flag:
10     print('''>>>>>>>>> 商品列表如下 <<<<<<<<<
11     \n序号\t名称\t\t价格/元\n''')
12     for index,i in enumerate(product_list):
13         print("%s\t%s\t\t%s"%(index,i[0],i[1]))
14         print('--------------------------------')
15     user_choice = input("请输入你想购买的商品的序号(按'q/Q'退出)>>:")
16     if user_choice.isdigit():
17         ''' 判断顾客是否输入数字 '''
18         user_choice = int(user_choice) # 强制类型转换
19         if user_choice>=0 and user_choice<len(product_list):
20             ''' 判断顾客购买的商品是否存在 '''
21             if balance >= product_list[user_choice][1]:
22                 ''' 判断顾客的工资余额是否足够购买所选商品 '''
23                 balance -= product_list[user_choice][1] # 计算余额
24                 cost += product_list[user_choice][1] # 统计花费
25                 shopping_cart.append(product_list[user_choice]) # 加入购物车
26                 print('%s 已经加入你的购物车,你的余额还剩 ¥%s'%(product_list[user_choice],balance))
27             else:
28                 print('抱歉,你的银行卡余额不足,请充值后再购买...')
29         else:
30             print('你要购买的商品不存在,请核对后再输入!')
31     elif user_choice == 'q' or user_choice=='Q':
32         ''' 顾客输入 q/Q 时退出购物 '''
33         if len(shopping_cart)>0:
34             ''' 判断顾客的购物车是否为空 '''
35             print('>>>>> 你的购物车商品清单如下 <<<<<')
36             for p in shopping_cart:
37                 ''' 输打印购物车商品列表和余额'''
38                 print('---\t%s\t\t¥%s\t---'%(p[0],p[1]))
39             print('你的消费金额为:¥%s ,工资余额为: ¥%s'%(cost,balance))         
40             exit_flag = True #退出循环
41         else:
42             print('你尚未购买商品...工资余额为:%s'%balance)
43             exit_flag = True #退出循环
44     else:
45         print('输入不合法!!!')

 

posted @ 2019-03-11 01:13  暮光微凉  阅读(441)  评论(0编辑  收藏  举报