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算法学习之计数排序实例
Dec 18 Python
用Python编写生成树状结构的文件目录的脚本的教程
May 04 Python
python根据京东商品url获取产品价格
Aug 09 Python
Python中表达式x += y和x = x+y 的区别详解
Jun 20 Python
python在每个字符后添加空格的实例
May 07 Python
对TensorFlow的assign赋值用法详解
Jul 30 Python
详解分布式任务队列Celery使用说明
Nov 29 Python
Python文件如何引入?详解引入Python文件步骤
Dec 10 Python
Python下简易的单例模式详解
Apr 08 Python
解决pycharm 工具栏Tool中找不到Run manager.py Task的问题
Jul 01 Python
pytorch实现手写数字图片识别
May 20 Python
pandas中pd.groupby()的用法详解
Jun 16 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数组函数序列之asort() - 对数组的元素值进行升序排序,保持索引关系
2011/11/02 PHP
php ios推送(代码)
2013/07/01 PHP
PHP配置把错误日志以邮件方式发送方法(Windows系统)
2015/06/23 PHP
YII2.0之Activeform表单组件用法实例
2016/01/09 PHP
php 获取文件行数的方法总结
2016/10/11 PHP
PHP中for循环与foreach的区别
2017/03/06 PHP
php基于session锁防止阻塞请求的方法分析
2017/08/07 PHP
firefox插件Firebug的使用教程
2010/01/02 Javascript
javascript 闭包疑问
2010/12/30 Javascript
JavaScript之IE的fireEvent方法详细解析
2013/11/20 Javascript
基于NodeJS的前后端分离的思考与实践(一)全栈式开发
2014/09/26 NodeJs
javascript中局部变量和全局变量的区别详解
2015/02/27 Javascript
jQuery控制cookie过期时间的方法
2015/04/07 Javascript
JavaScript中的setMilliseconds()方法使用详解
2015/06/11 Javascript
BootStrapTable服务器分页实例解析
2016/12/20 Javascript
js实现网页定位导航功能
2017/03/07 Javascript
Vue 2中ref属性的使用方法及注意事项
2017/06/12 Javascript
理解 javascript 中的函数表达式与函数声明
2017/07/07 Javascript
js判断用户是输入的地址请求的路径(实例讲解)
2017/07/18 Javascript
Angular 项目实现国际化的方法
2018/01/08 Javascript
实现Vue的markdown文档可以在线运行的方法示例
2018/12/11 Javascript
js实现图片实时时钟
2020/01/15 Javascript
[50:17]Newbee vs Serenity 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/18 DOTA
python时间整形转标准格式的示例分享
2014/02/14 Python
python中的格式化输出用法总结
2016/07/28 Python
Python简单实现网页内容抓取功能示例
2018/06/07 Python
把pandas转换int型为str型的方法
2019/01/29 Python
Python3 获取文件属性的方式(时间、大小等)
2020/03/12 Python
Python利用Xpath选择器爬取京东网商品信息
2020/06/01 Python
scrapy redis配置文件setting参数详解
2020/11/18 Python
瑞士国际航空官网:SWISS
2016/07/21 全球购物
光信息科学与技术专业职业生涯规划
2014/03/13 职场文书
我的中国梦演讲稿500字
2014/08/19 职场文书
公司员工安全协议书
2014/11/21 职场文书
社区低保工作总结2015
2015/07/23 职场文书
python用海龟绘图写贪吃蛇游戏
2021/06/18 Python