商品程序

import json

FILENAME = 'product.json'

def op_file_json(file_name,dic=None):
if dic:
with open(file_name,'w',encoding='utf-8') as fw:
json.dump(dic,fw,ensure_ascii=False,indent=4)
else:
with open(file_name,'a+',encoding='utf-8') as fr:
fr.seek(0)
content = fr.read()
if content:
result = json.loads(content)
else:
result = {}
return result

def is_price(s): #形式参数
s = str(s)
if s.count('.') == 1:#这个是判断正小数
left,right = s.split('.') #1.74 ['1','74']
if left.isdigit() and right.isdigit() and right>'0':
return True
if s.isdigit() and s >'0':#判断是否为大于0 的整数
return True
return False

def add_product():
all_product = op_file_json(FILENAME) #获取到所有的产品
name = input('name:').strip()
count = input('count:').strip() #s1 s3 1.s
price = input('price:').strip()
if name and count and price:
if count.isdigit() and count >'0' and is_price(price):
if name in all_product:
print('商品已经存在了')
else:
all_product[name]={"price":price,"count":count}
op_file_json(FILENAME,all_product)
print('添加成功!')
else:
print('数量、价格不合法')
else:
print('必填项不能为空!')

def modify_product():
all_product = op_file_json(FILENAME) #获取到所有的产品
name = input('name:').strip()
count = input('count:').strip() #s1 s3 1.s
price = input('price:').strip()
if name and count and price:
if count.isdigit() and count >'0' and is_price(price):
if name in all_product:
all_product[name] = {"price": price, "count": count}
op_file_json(FILENAME, all_product)
print('修改成功!')
else:
print('商品不存在!')
else:
print('数量、价格不合法')
else:
print('必填项不能为空!')

def delete_product():
all_product = op_file_json(FILENAME) #获取到所有的产品
name = input('name:').strip()
if not name:
print('没有输入商品名称!')
elif name not in all_product:
print('商品不存在!')
else:
all_product.pop(name)
op_file_json(FILENAME,all_product)
print('删除成功!')

def show_product():
all_product = op_file_json(FILENAME) #获取到所有的产品
name = input('请输入商品名称,什么也不输入的话,就代表查看所有的商品:').strip()
if name!='' and name in all_product:
print(all_product[name])
elif name=='':
print(all_product)
else:
print('商品不存在!')


func_dic = {"1":add_product,"2":modify_product,"3":delete_product,"4":show_product}

for i in range(3):
choice = input('请输入你的选择!'
'1、添加商品'
'2、修改商品'
'3、删除商品'
'4、查看商品:').strip()
if choice in func_dic:
func_dic[choice]()
else:
print('输入选项错误!')

#函数即变量
原文地址:https://www.cnblogs.com/Dorami/p/11040151.html