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 相关文章推荐
pygame播放音乐的方法
May 19 Python
Python 专题六 局部变量、全局变量global、导入模块变量
Mar 20 Python
python 通过麦克风录音 生成wav文件的方法
Jan 09 Python
​如何愉快地迁移到 Python 3
Apr 28 Python
Python项目 基于Scapy实现SYN泛洪攻击的方法
Jul 23 Python
python命名空间(namespace)简单介绍
Aug 10 Python
python 调用pyautogui 实时获取鼠标的位置、移动鼠标的方法
Aug 27 Python
Django实现文件上传下载功能
Oct 06 Python
Python random模块制作简易的四位数验证码
Feb 01 Python
关于Tensorflow分布式并行策略
Feb 03 Python
Scrapy 配置动态代理IP的实现
Sep 28 Python
Python爬虫模拟登陆哔哩哔哩(bilibili)并突破点选验证码功能
Dec 21 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 采集获取指定网址的内容
2010/01/05 PHP
分享PHP header函数使用教程
2013/09/05 PHP
php判断文件上传类型及过滤不安全数据的方法
2014/12/17 PHP
PHP实现负载均衡的加权轮询方法分析
2018/08/22 PHP
laravel框架与其他框架的详细对比
2019/10/23 PHP
thinkphp5实现微信扫码支付
2019/12/23 PHP
读jQuery之十一 添加事件核心方法
2011/07/31 Javascript
jQuery事件之键盘事件(ctrl+Enter回车键提交表单等)
2014/05/11 Javascript
基于insertBefore制作简单的循环插空效果
2015/09/21 Javascript
基于PHP和Mysql相结合使用jqGrid读取数据并显示
2015/12/02 Javascript
JS创建事件的三种方法(实例代码)
2016/05/12 Javascript
jquery层级选择器的实现(匹配后代元素div)
2016/09/05 Javascript
js变量提升深入理解
2016/09/16 Javascript
javascript中的后退和刷新实现方法
2016/11/10 Javascript
详解项目升级到vue-cli3的正确姿势
2019/01/28 Javascript
layui+jquery支持IE8的表格分页方法
2019/09/28 jQuery
[01:00:59]VP VS VG Supermajor小组赛胜者组第二轮 BO3第二场 6.2
2018/06/03 DOTA
讲解Python中fileno()方法的使用
2015/05/24 Python
解决Python字典写入文件出行首行有空格的问题
2017/09/27 Python
pandas将DataFrame的列变成行索引的方法
2018/04/10 Python
Pandas 数据框增、删、改、查、去重、抽样基本操作方法
2018/04/12 Python
python实现简单的单变量线性回归方法
2018/11/08 Python
Python爬虫实现selenium处理iframe作用域问题
2021/01/27 Python
python实现发送邮件
2021/03/02 Python
HTML5中使用postMessage实现两个网页间传递数据
2016/06/22 HTML / CSS
de Bijenkorf比利时官网:荷兰最知名的百货商店
2017/06/29 全球购物
网络公司美工设计工作个人的自我评价
2013/11/03 职场文书
路政管理专业推荐信
2013/11/11 职场文书
2014教师年度工作总结
2014/11/10 职场文书
清洁员岗位职责
2015/02/15 职场文书
2015暑期爱心支教策划书
2015/07/14 职场文书
重阳节简报
2015/07/20 职场文书
小学同学聚会感言
2015/07/30 职场文书
某药房的新员工入职告知书!
2019/07/15 职场文书
导游词之包公祠
2019/11/25 职场文书
关于vue中如何监听数组变化
2021/04/28 Vue.js