zoukankan      html  css  js  c++  java
  • python习题:用文件方式编写购物车程序,添加,查看和删除

    #2、写一个添加商品的程序    必做
    # 1、添加商品
    #商品名称
    #价格
    #数量
    #颜色
    # 2、查看商品
    # 3、删除商品
    #输入商品名称


    PRODUCT_FILE='products' # 大写变量名称的代表 常量

    def op_file(filename,content=None):
    f = open(filename,'a+',encoding='utf-8')
    f.seek(0)
    if content!=None:
    f.truncate()
    f.write(str(content))
    f.flush()
    else:
    res = f.read()
    if res:
    products = eval(res)
    else:
    products = {}
    return products
    f.close()

    def check_price(s):# 100
    s = str(s)
    if s.count('.') == 1:
    s_list = s.split('.') #[1,5] [-s,55]
    left = s_list[0] # -s ['','s']
    right = s_list[1]
    if left.isdigit() and right.isdigit(): #正小数
    return True
    elif s.isdigit() and int(s)>0:#整数
    return True
    return False

    def check_count(count):
    if count.isdigit():
    if int(count)>0:
    return True
    return False

    def add_product():
    while True:
    name = input('name:').strip()
    price = input('price:').strip()
    count = input('count:').strip()
    color = input('color:').strip()
    if name and price and count and color:
    products = op_file(PRODUCT_FILE)
    if name in products:
    print('商品已经存在')
    elif not check_price(price): #价格不合法,价格不合法Fasle
    print('价格不合法')
    elif not check_count(count):#数量不合法
    print('商品数量不合法!')
    else:
    product = {'color':color,'price':'%.2f'%float(price),'count':count}
    products[name]=product
    op_file(PRODUCT_FILE,products)
    print('商品添加成功!')
    break
    else:
    print('必填参数未填!')


    def view_products():
    products = op_file(PRODUCT_FILE)
    if products:
    for k in products:
    print('商品名称【%s】,商品信息【%s】'%(k,products.get(k)))
    else:
    print('当前没有商品')

    def del_product():
    while True:
    name = input('name:').strip()
    if name:
    products = op_file(PRODUCT_FILE)
    if products:
    if name in products:
    products.pop(name)
    op_file(PRODUCT_FILE,products)
    print('删除成功!')
    break
    else:
    print('你输入的商品名称不存在,请重新输入!')
    else:
    quit('当前没有商品!')

    else:
    print('必填参数未填!')

    def start():
    choice = input('请输入你的选择:1、添加商品 2、查看商品 3、删除商品,q退出:').strip()
    if choice == '1':
    add_product()
    elif choice=='2':
    view_products()
    elif choice=='3':
    del_product()
    elif choice=='q':
    quit('谢谢光临')
    else:
    print('输入错误!')
    return start()

    start()
  • 相关阅读:
    【OpenStack】OpenStack系列16之OpenStack镜像制作
    【OpenStack】OpenStack系列15之OpenStack高可用详解
    【OpenStack】OpenStack系列14之Dashboard定制开发
    【OpenStack】OpenStack系列13之Nova源码解析与API扩展
    linux之scp命令
    阿里大鱼短信平台
    count(1)与count(*)
    java中枚举类到高级使用
    idea中mybatis-plugin破解
    mmall项目之问题一(mavenplugin问题)
  • 原文地址:https://www.cnblogs.com/blackbird0423/p/8310400.html
Copyright © 2011-2022 走看看