商品管理的小程序

#2、商品管理的程序,商品信息都存在一个json串里面
# 添加商品
# 1、添加 商品名称 价格 颜色 数量
# 2、查看商品信息
# 3、删除
# 4、修改 商品名称 价格 颜色 数量
# 5、操作文件
#

import json

FILE_NAME = 'goods.json'
def op_file(name,content=None):
if content:
with open(name,'w',encoding='utf-8') as fw:
json.dump(content,fw,indent=4,ensure_ascii=False)
else:
with open(name,encoding='utf-8') as fr:
res = json.load(fr)
return res
all_goods = op_file(FILE_NAME)

def check_price(price):
price = str(price)
if price.isdigit():
price = int(price)
if price>0:
return True
else:
if price.count('.')==1:
tmp = price.split('.')
#0.0
left = tmp[0]
right = tmp[1]
# 1.00

if left.isdigit() and right.isdigit() and int(right)>0: #1.0
return True
elif left.isdigit() and right.isdigit() and int(left)>0: # 0.1
return True
return False

def get_good_info():
while True:
good_name = input('商品名称:').strip()
price = input('price:').strip()
count = input('count:').strip()
color = input('color:').strip()
if good_name and price and count and color:
if not check_price(price):
print('价格输入不合法,必须大于0')
elif not count.isdigit() and int(count)<1:
print('数量不合法')
else:
return good_name,price,count,color
else:
print('输入不能为空!')

def add_good():
good_name,price,count,color = get_good_info()
if good_name not in all_goods:
all_goods[good_name]= {
'price':price,
'count':count,
'color':color
}
op_file(FILE_NAME,all_goods)
print('添加完成!')
else:
print('商品已经存在!')

def update_good():
good_name,price,count,color = get_good_info()
if good_name in all_goods:
all_goods[good_name]= {
'price':price,
'count':count,
'color':color
}
op_file(FILE_NAME,all_goods)
print('修改完成!')
else:
print('商品不存在!')

def query_good():
good_name = input('商品名称:').strip()
if good_name in all_goods:
print(all_goods.get(good_name))
else:
print('商品不存在')

def delete_good():
good_name = input('商品名称:').strip()
if good_name in all_goods:
all_goods.pop(good_name)
op_file(FILE_NAME,all_goods)
else:
print('商品不存在')

def main():
for i in range(3):
choice = input('请输入你的选择'
'1、添加'
'2、修改'
'3、删除'
'4、查看'
'5、退出')
if choice=="1":
add_good()
elif choice=="2":
update_good()
elif choice=="3":
delete_good()
elif choice=="4": query_good() elif choice=="5": quit('程序退出') else: print('输入错误,请重新输入!') return main()main()
原文地址:https://www.cnblogs.com/jiadan/p/8992938.html