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数据结构之单链表详解
Sep 12 Python
Python numpy 提取矩阵的某一行或某一列的实例
Apr 03 Python
python 遍历目录(包括子目录)下所有文件的实例
Jul 11 Python
python+selenium实现自动抢票功能实例代码
Nov 23 Python
详解python中@的用法
Mar 27 Python
python django下载大的csv文件实现方法分析
Jul 19 Python
python:按行读入,排序然后输出的方法
Jul 20 Python
运用PyTorch动手搭建一个共享单车预测器
Aug 06 Python
基于Python生成个性二维码过程详解
Mar 05 Python
python实点云分割k-means(sklearn)详解
May 28 Python
Python数据相关系数矩阵和热力图轻松实现教程
Jun 16 Python
python中判断数字是否为质数的实例讲解
Dec 06 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设计模式 DAO(数据访问对象模式)
2011/06/26 PHP
PHP大转盘中奖概率算法实例
2014/10/21 PHP
discuz图片顺序混乱解决方案
2015/07/29 PHP
thinkphp5实现无限级分类
2019/02/18 PHP
载入进度条 效果
2006/07/08 Javascript
Mootools 1.2教程 函数
2009/09/15 Javascript
原生js实现查找/添加/删除/指定元素的class
2013/04/12 Javascript
jquery 按钮状态效果 正常、移上、按下
2013/08/12 Javascript
利用JS判断用户是否上网(连接网络)
2013/12/23 Javascript
Javscript调用iframe框架页面中函数的方法
2014/11/01 Javascript
在AngularJS中使用AJAX的方法
2015/06/17 Javascript
微信小程序 网络API Websocket详解
2016/11/09 Javascript
node.js版本管理工具n无效的原理和解决方法
2016/11/24 Javascript
Canvas + JavaScript 制作图片粒子效果
2017/02/08 Javascript
Vue.js 2.0 移动端拍照压缩图片预览及上传实例
2017/04/27 Javascript
jQuery.Form实现Ajax上传文件同时设置headers的方法
2017/06/26 jQuery
Vue中建立全局引用或者全局命令的方法
2017/08/21 Javascript
vee-validate vue 2.0自定义表单验证的实例
2018/08/28 Javascript
详解JS判断页面是在手机端还是在PC端打开的方法
2019/04/26 Javascript
js中比较两个对象是否相同的方法示例
2019/09/02 Javascript
[02:54]辉夜杯主赛事第二日败者组 iG.V赛后采访
2015/12/26 DOTA
[00:52]黑暗之门更新 新英雄孽主驾临DOTA2
2016/08/24 DOTA
在Mac OS上部署Nginx和FastCGI以及Flask框架的教程
2015/05/02 Python
python3.4用循环往mysql5.7中写数据并输出的实现方法
2017/06/20 Python
在python中安装basemap的教程
2018/09/20 Python
python读出当前时间精度到秒的代码
2019/07/05 Python
Python学习笔记之For循环用法详解
2019/08/14 Python
django queryset相加和筛选教程
2020/05/18 Python
米兰网婚纱礼服法国网上商店:Milanoo法国
2016/08/20 全球购物
请描述一下”is a”关系和”has a”关系
2015/02/03 面试题
大二学期个人自我评价
2014/01/13 职场文书
小学安全教育材料
2014/02/17 职场文书
2014收银员工作总结范文
2014/12/16 职场文书
行政人事专员岗位职责
2015/04/07 职场文书
2016学习医德医风心得体会
2016/01/25 职场文书
大学生入党自我鉴定范文
2019/06/21 职场文书