商品管理小程序

需求
1、商品存在文件里面
1、添加商品
输入产品名称、颜色、价格
要校验商品是否存在,价格是否合法
输入是否为空
2、修改商品信息
输入产品名称、颜色、价格
要校验商品是否存在,价格是否合法
输入是否为空
3、查看商品信息
输入商品名称
输入all就展示全部商品
输入的是其他的商品名称,
4、删除商品
输入商品名称
import json
filename = 'product.json'
#读文件
def read_product():
    with open(filename, 'a+',encoding='utf-8') as fr:
        fr.seek(0)
        content = fr.read()
        if content:
            dic = json.loads(content)
        else:
            dic = {}
    return dic
#写入文件
def write_product(product):
    with open(filename,'w',encoding='utf-8')  as fw:
        json.dump(product, fw, ensure_ascii=False, indent=4)

#判断价格是否合法(不能为负数)
def check_float(num):
    num = str(num)
    if num.count('.') ==1:
        left,right = num.split('.')
        if left.isdigit()  and right.isdigit():
            print('正小数')
            return float(num)
    elif num.isdigit():
        if int(num) > 0:
            return int(num)
    return  False

#添加商品
def add_product():
    all_product = read_product()
    p_name = input('请输入产品名称:').strip()
    p_color = input('请输入产品颜色:').strip()
    p_price = input('请输入产品价格:').strip()
    if not p_name or not p_color or not p_price:
        print('商品输入不能为空')
    elif p_name in all_product:
        print('商品已存在')
    elif not check_float(p_price):
        print('价格不合法')
    else:
        all_product[p_name] = {"color":p_color,"price":p_price}
        write_product(all_product)
        print('添加商品成功')

#删除商品
def del_product():
    all_product = read_product()
    p_name = input('请输入要删除的商品:')
    if not p_name:
        print('输入不能为空!')
    elif p_name not in all_product:
        print('商品不存在')
    else:
        del all_product[p_name]
        write_product(all_product)
        print('删除商品成功')


#查看商品
def show_product():
    all_product = read_product()
    if all_product:
        print(all_product)
    else:
        print('暂时没有产品')


#更新商品
def update_product():
    all_product = read_product()
    p_name = input('请输入要修改的商品名称:').strip()
    p_color = input('输入要修改的颜色:').strip()
    p_price = input('输入商品的价格:').strip()
    if not p_name:
        print('商品名称不能为空')
    elif p_name not in all_product:
        print('商品不存在')
    elif not check_float(p_price):
        print('价格输入不合法')
    else:
        all_product[p_name] ={"color":p_color,"price":p_price}
        write_product(all_product)
        print('商品更新成功!')


choice = input('请输入你的选择:1、添加2、修改 3、删除 4、查看:')
if choice=='1':
    add_product()
elif choice=='2':
    update_product()
elif choice =='3':
    update_product()
elif choice == '4':
    show_product()
else:
    print('请输入1、2、3、4的其中一个数字')

 

posted @ 2019-10-05 10:40  xmb  阅读(333)  评论(0)    收藏  举报