Python实现的购物车功能示例


Posted in Python onFebruary 11, 2018

本文实例讲述了Python实现的购物车功能。分享给大家供大家参考,具体如下:

这里尝试用python实现简单的购物车程序。。。

基本要求:

用户输入工资,然后打印购物菜单
用户可以不断的购买商品,直到余额不够为止
退出时打印用户已购买的商品和剩余金额。。。

代码:

#!/usr/env python
#coding:utf-8
import re,math
def get_customer_salary():
  while True:
    salary=raw_input('Please input your monthly salary(a positive integer):')
    if __is_valid_num(salary):
      return int(salary)
    else:
      print '[warn] Please input a valid number!'
def __is_valid_num(num):
  p=re.compile(r'^\d+$')
  m=p.match(num)
  if m:
    return True
  else:
    return False
def get_customer_selection():
  while True:
    selection=raw_input('Please enter the goods number you want to buy:')
    if __is_valid_num(selection):
      if __is_a_valid_selection(int(selection)):
        return int(selection)
      else:
        print '[warn] Please enter a valid selection number'
    else:
      print '[warn] Please enter a valid number!\n'
def __is_a_valid_selection(selection):
  if 1<=selection<=get_total_amount_of_products():
    return True
  else:
    return False
def get_products_list():
  return {'Flower':50,'Perfume':300,'Shoes':600,'Clothing':800,'Alcohol':300,
       'Makeup':800,'Bike':1500,'Car':200000,'Apartment':5000000}
def get_total_amount_of_products():
  return len(get_products_list())
def mapping_type_code_for_products():
  return ['Flower','Perfume','Shoes','Clothing','Alcohol','Makeup','Bike','Car','Apartment']
def get_product_price(type_code):
  return get_products_list()[get_product_name(type_code)]
def get_product_name(type_code):
  return mapping_type_code_for_products()[type_code-1]
def get_lowest_price_of_products():
  price_list=[]
  for k,v in get_products_list().items():
    price_list.append(v)
  return min(price_list)
def get_highest_price_of_produces():
  price_list=[]
  for k,v in get_products_list().items():
    price_list.append(v)
  return max(price_list)
def still_can_buy_something(left_money):
  if left_money<get_lowest_price_of_products():
    return False
  else:
    return True
def still_want_to_buy_something():
  while True:
    answer=raw_input('Do you still want to buy something?(y/n):')
    result=is_a_valid_answer(answer)
    if result=='yes':return True
    if result=='no':return False
    print '[warn] Please enter [yes/no] or [y/n]!\n'
def is_a_valid_answer(answer):
  yes_pattern=re.compile(r'^[Yy][Ee][Ss]$|^[Yy]$')
  no_pattern=re.compile(r'^[Nn][Oo]$|^[Nn]$')
  if yes_pattern.match(answer):return 'yes'
  if no_pattern.match(answer):return 'no'
  return False
def show_shopping_list():
  counter=1
  for i in mapping_type_code_for_products():
    print '''''(%d) %s: %s RMB''' % (counter,i+' '*(10-len(i)),str(get_products_list()[i]))
    counter+=1
def is_affordable(left_money,product_price):
  if left_money>=product_price:
    return True
  else:
    return False
def time_needed_to_work_for_buying_products(salary,price):
  result=float(price)/salary
  return get_formatting_time(int(math.ceil(result)))
def get_formatting_time(months):
  if months<12:return ('%d months' % months)
  years=months/12
  months=months%12
  return ('%d years,%d months' % (years,months))
#主程序从这里开始
if __name__=='__main__':
  salary=get_customer_salary() #获取月工资
  total_money=salary
  shopping_cart=[] #初始化购物车
  while True:
    show_shopping_list() #打印购物列表
    #判断剩余资金是否能够购买列表中的最低商品
    if still_can_buy_something(total_money):
      selection=get_customer_selection() #获取用户需要购买的商品编号
      product_price=get_product_price(selection)#获取商品的价格
      product_name=get_product_name(selection)#获取商品的名称
      if total_money>=product_price:
        total_money-=product_price
        #打印购买成功信息
        print 'Congratulations!You bought a %s successfully!\n' % product_name
        shopping_cart.append(product_name)#将商品加入购物车
        print 'You still have %d RMB left\n' % total_money #打印剩余资金
        #判断是否还想购买其他商品
        if not still_want_to_buy_something():
          print 'Thank you for coming!'
          break
      else:
        #输出还需要工作多久才能购买
        format_time=time_needed_to_work_for_buying_products(salary,product_price-total_money)
        print 'Sorry,you can not afford this product!\n'
        print "You have to work '%s' to get it!\n" % format_time
        #判断是否还想购买其他商品
        if not still_want_to_buy_something():break
    else:
      print 'Your balance is not enough and can not continue to buy anything.'
      break
  #打印购物车列表
  print 'Now,your balance is %d,and\nYou have buy %s' % (total_money,shopping_cart)

运行效果:

Python实现的购物车功能示例

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Django的session中对于用户验证的支持
Jul 23 Python
Python实现PS滤镜特效Marble Filter玻璃条纹扭曲效果示例
Jan 29 Python
Python中存取文件的4种不同操作
Jul 02 Python
flask入门之表单的实现
Jul 18 Python
Python文件打开方式实例详解【a、a+、r+、w+区别】
Mar 30 Python
用python建立两个Y轴的XY曲线图方法
Jul 08 Python
Python如何调用外部系统命令
Aug 07 Python
在pytorch 中计算精度、回归率、F1 score等指标的实例
Jan 18 Python
以SQLite和PySqlite为例来学习Python DB API
Feb 05 Python
python 代码运行时间获取方式详解
Sep 18 Python
有趣的二维码:使用MyQR和qrcode来制作二维码
May 10 Python
一篇文章带你了解Python和Java的正则表达式对比
Sep 15 Python
python PyTorch参数初始化和Finetune
Feb 11 #Python
Python装饰器用法示例小结
Feb 11 #Python
python PyTorch预训练示例
Feb 11 #Python
TensorFlow中权重的随机初始化的方法
Feb 11 #Python
python的staticmethod与classmethod实现实例代码
Feb 11 #Python
Python语言的变量认识及操作方法
Feb 11 #Python
利用Opencv中Houghline方法实现直线检测
Feb 11 #Python
You might like
人尽可用的Windows技巧小贴士之下篇
2007/03/22 PHP
基于PHP array数组的教程详解
2013/06/05 PHP
ThinkPHP删除栏目(实现批量删除栏目)
2017/06/21 PHP
调用innerHTML之后onclick失效问题的解决方法
2014/01/28 Javascript
Jquery实现兼容各大浏览器的Enter回车切换输入焦点的方法
2014/09/01 Javascript
javascript最基本的函数汇总
2015/06/25 Javascript
jQuery动态星级评分效果实现方法
2015/08/06 Javascript
gulp-htmlmin压缩html的gulp插件实例代码
2016/06/06 Javascript
AngularJS入门教程之路由机制ngRoute实例分析
2016/12/13 Javascript
JS传参及动态修改页面布局
2017/04/13 Javascript
微信小程序手机号码验证功能的实例代码
2018/08/28 Javascript
Vue请求JSON Server服务器数据的实现方法
2018/11/02 Javascript
jQuery实现的网站banner图片无缝轮播效果完整实例
2019/01/28 jQuery
基于Vue SEO的四种方案(小结)
2019/07/01 Javascript
浅谈vue中组件绑定事件时是否加.native
2019/11/09 Javascript
微信小程序实现音乐播放页面布局
2020/12/11 Javascript
js闭包的9个使用场景
2020/12/29 Javascript
[06:13]DOTA2进化论(修改版)
2013/10/08 DOTA
[01:12:40]DOTA2-DPC中国联赛 正赛 DLG vs XG BO3 第三场 1月25日
2021/03/11 DOTA
[08:08]DOTA2-DPC中国联赛2月28日Recap集锦
2021/03/11 DOTA
详解在Python和IPython中使用Docker
2015/04/28 Python
python和ruby,我选谁?
2017/09/13 Python
Python爬虫之网页图片抓取的方法
2018/07/16 Python
浅析python中numpy包中的argsort函数的使用
2018/08/30 Python
详解PyTorch中Tensor的高阶操作
2019/08/18 Python
pycharm导入源码的具体步骤
2020/08/04 Python
基于Python的图像阈值化分割(迭代法)
2020/11/20 Python
python基于openpyxl生成excel文件
2020/12/23 Python
Python绘制数码晶体管日期
2021/02/19 Python
英国版MAC彩妆品牌:Illamasqua
2018/04/18 全球购物
ABOUT YOU罗马尼亚:超过600个时尚品牌
2019/09/19 全球购物
英语专业应届生求职信范文
2013/11/15 职场文书
好邻里事迹材料
2014/01/16 职场文书
局机关干部群众路线个人对照检查材料思想汇报
2014/10/05 职场文书
尊师重教主题班会
2015/08/14 职场文书
手把手教你使用TensorFlow2实现RNN
2021/07/15 Python