Python学习-购物车程序

程序:购物车程序

需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
  4. 可随时退出,退出时,打印已购买商品和余额

程序如下:

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 # @Time    : 2018/4/28 16:23
 4 # @Author  : yang
 5 # @File    : Shopping_Cart_Program01.py
 6 # @Software: PyCharm
 7 #定义商品列表
 8 product_list = [('Iphone',6000),
 9                 ('MAC Pro',9800),
10                 ('Bike',800),
11                 ('Watch',10600),
12                 ('Coffee',31),
13                 ('Alex python',120),]
14 shopping_list = []   #定义空的购物车列表
15 #输入工资
16 salary = input('Input your salary:')
17 if salary.isdigit():
18     salary = int(salary)
19     #循环输入需要购买的商品编号
20     while True:
21         # enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列
22         for index,item in enumerate(product_list):    
23             print(index,item)      #打印输出带编号的商品列表
24         user_choice = input('选择要买的商品编号>>>:')    #输入要购买的商品编号
25         if user_choice.isdigit()==False and user_choice.upper() != 'Q':
26             print('33[1;43m你输入的商品编号不合法!33[0m')
27             exit()
28         elif user_choice.isdigit()==True:       #判断输入的字符串是否由数字组成
29             user_choice = int(user_choice)
30             if user_choice < len(product_list) and user_choice >=0:
31                 p_item = product_list[user_choice]
32                 if p_item[1] <= salary:    #买得起
33                     shopping_list.append(p_item)
34                     salary -= p_item[1]
35                     print('将商品%s添加到购物车,剩余金额33[1;31;42m%s33[0m'%(p_item,salary))
36                     #高亮显示:开头部分:33[显示方式;前景色;背景色m + 结尾部分:33[0m
37                 else:    #买不起
38                     print('33[1;41m你的余额只剩[%s]啦,还买个毛线!33[0m'%salary)
39             else:
40                 print('33[1;41m商品%s不存在!33[0m'%user_choice)
41 
42         #退出购物车程序:打印输出购物列表和余额
43         elif user_choice.upper() == 'Q':
44             print('---------------shopping list---------')
45             for p in shopping_list:
46                 print(p)
47             print('你的余额还剩:',salary)
48             exit()
49         else:
50             exit()
51 else:     #如果输入的工资不合法,则退出程序
52     print('您输入的工资不合法!')
53     exit()

注:程序参照老男孩Alex,附博客地址:http://www.cnblogs.com/alex3714/articles/5717620.html

原文地址:https://www.cnblogs.com/yangshijia/p/8969175.html