新浦京81707con > 功能介绍 > Python3实现购物车功能,Python实现购物车购物小程

原标题:Python3实现购物车功能,Python实现购物车购物小程

浏览次数:73 时间:2019-06-12

概要

本文实例讲述了Python达成的购物车成效。分享给我们供大家参照他事他说加以调查,具体如下:

正文实例为我们分享了Python三贯彻购物车成效的切实可行代码,供大家参谋,具体内容如下

按理说,大家入门的首先个小程序都应当是Hello World。因为比较轻易,小编这也就不做过多的亲自过问 了。
上面是自己写的三个小程序。首要用来练习Python的主导语法,以及入门。

此处品尝用python完成轻巧的购物车程序。。。

购物车必要:

主要贯彻效益

基本须要:

一、运营程序后,输入用户名密码后,假诺是率先次登入,让用户输入薪水,然后打字与印刷商品列表

  • 渴求用户输入本身预想消费额度.
  • 彰显现存商品新闻,须求用户挑选
  • 用户选拔相应商品标号后(注意看清是还是不是超越预想消费额度等操作),保存到购物车
  • 用户退出后出示购物车音信以及剩余额度情形

用户输入工资,然后打字与印刷购物菜单
用户能够不停的买入商品,直到余额非常不足结束
剥离时打字与印刷用户已购买的物品和剩下金额。。。

2、允许用户依据商品编号购买商品

代码:

代码:

叁、用户挑选商品后,检查评定余额是或不是够,够就直接扣款,非常不足就提醒

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@author: 烽火
@license: Apache Licence
@file: shopping.py
@time: 6/16/17 10:05 AM
"""

goods = [
  ("IPhone", 5800),
  ("Watch", 2000),
  ("MacBook", 12000)]

goods_cart = []

mybudget = input("请输入您的预算:")

# 不考虑是小数的情况
while not mybudget.isdigit():
  mybudget = input("输入有误,请重新输入您的预算:")
mybudget = int(mybudget);

while True:
  print("商品列表".center(50, "-"))
  print("编号".center(8, " "), "名称".ljust(30, " "), "价格".ljust(10, " "))
  for i in enumerate(goods):
    print(str(i[0]).center(10, " "), str(i[1][0]).ljust(31, " "), str(i[1][1]).ljust(10, " "))

  user_choose = input("请输入您的选择:")

  if user_choose.isdigit():
    user_choose = int(user_choose)
    if user_choose >= 0 and user_choose < len(goods):
      if (mybudget - goods[user_choose][1]) >= 0:
        goods_cart.append(goods[user_choose])
        mybudget -= goods[user_choose][1]
        print("预算还有%d" % mybudget)
      else:
        print("预算不够啦~")
    else:
      print("不存在该商品~")

  elif user_choose == 'q':
    break

  else:
    print("您的输入有误~")

print("预算还剩%d了" %(mybudget))
print("购物车商品信息".center(50, "-"))

for i in enumerate(goods_cart):
    print(str(i[0]).center(10, " "), str(i[1][0]).ljust(31, " "), str(i[1][1]).ljust(10, " "))
#!/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
  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 leftn' % 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,andnYou have buy %s' % (total_money,shopping_cart)

四、可随时退出,退出时,打字与印刷已购进商品和余额

蒲京娱乐场网站手机版,运行结果

运作效果:

伍、在用户使用进度中, 关键输出,如余额,商品已加盟购物车等消息,需高亮展现

本文由新浦京81707con发布于功能介绍,转载请注明出处:Python3实现购物车功能,Python实现购物车购物小程

关键词: 新浦京81707con

上一篇:Web框架Tornado运行和部署,用户指南

下一篇:没有了