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 相关文章推荐
python、java等哪一门编程语言适合人工智能?
Nov 13 Python
Python线性回归实战分析
Feb 01 Python
Tensorflow 利用tf.contrib.learn建立输入函数的方法
Feb 08 Python
Python实现批量修改图片格式和大小的方法【opencv库与PIL库】
Dec 03 Python
python selenium执行所有测试用例并生成报告的方法
Feb 13 Python
对python多线程SSH登录并发脚本详解
Feb 14 Python
通过PYTHON来实现图像分割详解
Jun 26 Python
Python如何应用cx_Oracle获取oracle中的clob字段问题
Aug 27 Python
详解python路径拼接os.path.join()函数的用法
Oct 09 Python
Python如何基于smtplib发不同格式的邮件
Dec 30 Python
给ubuntu18安装python3.7的详细教程
Jun 08 Python
聊聊python在linux下与windows下导入模块的区别说明
Mar 03 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
PHP下打开URL地址的几种方法小结
2010/05/16 PHP
基于curl数据采集之单页面采集函数get_html的使用
2013/04/28 PHP
php支持断点续传、分块下载的类
2016/05/02 PHP
PHP GD库相关图像生成和处理函数小结
2016/09/30 PHP
PHP架构及原理知识点详解
2019/12/22 PHP
Javascript 类型转换方法
2010/10/24 Javascript
鼠标滚轴控制文本框值的JS代码
2013/11/19 Javascript
jQuery使用before()和after()在元素前后添加内容的方法
2015/03/26 Javascript
JavaScript中指定函数名称的相关方法
2015/06/04 Javascript
四种参数传递的形式——URL,超链接,js,form表单
2015/07/24 Javascript
jQuery EasyUI 布局之动态添加tabs标签页
2015/11/18 Javascript
Angular.JS通过指令操作DOM的方法
2017/05/10 Javascript
集成vue到jquery/bootstrap项目的方法
2018/02/10 jQuery
vue2中使用less简易教程
2018/03/27 Javascript
Node.js console控制台简单用法分析
2019/01/04 Javascript
JavaScript闭包与作用域链实例分析
2019/01/21 Javascript
JS实现点击li标签弹出对应的索引功能【案例】
2019/02/18 Javascript
vue操作动画的记录animate.css实例代码
2019/04/26 Javascript
微信小程序实现卡片左右滑动效果的示例代码
2019/05/01 Javascript
浅谈react-router@4.0 使用方法和源码分析
2019/06/04 Javascript
微信小程序实现左侧滑栏过程解析
2019/08/26 Javascript
layui之数据表格--与后台交互获取数据的方法
2019/09/29 Javascript
理解Python垃圾回收机制
2016/02/12 Python
Python实现打印螺旋矩阵功能的方法
2017/11/21 Python
对python 多个分隔符split 的实例详解
2018/12/20 Python
解决pyinstaller打包发布后的exe文件打开控制台闪退的问题
2019/06/21 Python
pandas分批读取大数据集教程
2020/06/06 Python
自定义html标记替换html5新增元素
2008/10/17 HTML / CSS
解析浏览器的一些“滚动”行为鉴赏
2019/09/16 HTML / CSS
护理专业自荐信
2013/12/03 职场文书
建筑经济管理专业求职信分享
2014/01/06 职场文书
简单的项目建议书模板
2014/03/12 职场文书
怎么写工作检讨书
2014/11/16 职场文书
终止解除劳动合同证明书
2015/06/17 职场文书
我国拿下天问一号火星着陆区附近 22 个地理实体命名:平乐、西柏坡、古田、漠河等
2022/04/29 数码科技
python如何读取和存储dict()与.json格式文件
2022/06/25 Python