• 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()
  • 相关阅读:
    【WP开发】WebView控件应用要点
    【WP开发】认清“不透明度”与“可见性”的区别
    分享:自学编程的方法
    <C#>找出数组中重复次数最多的数值
    【WP 8.1开发】上下文菜单
    【WP 8.1开发】同时更新多种磁贴
    【WP开发】如何处理溢出的文本
    lnmp/nginx系统真正有效的图片防盗链完整设置详解
    PHP自动加载SPL的四种处理方式
    算法笔记-判断链表保存的字符串是否是回文
  • 原文地址:https://www.cnblogs.com/blackbird0423/p/8310400.html
Copyright © 2020-2023  润新知