#、添加
#、商品名称
#、要从文件里面把所有的商品读出来
#、价格
#、写一个方法判断是否为合理的价格
#、数量
#整数
# product = {
# "爱疯差":{
# "price":999.98,
# "count":
# },
# "car":{
# "price":,
# "count":
# }
# }
# product['mac'] = {"price":,"count":}
# write(product)
# 写入文件,最新的商品写进去
#、删除
# 、商品名称
# 、要从文件里面把所有的商品读出来
# product = {
# "爱疯差": {
# "price": 999.98,
# "count":
# },
#
# }
# product.pop('car')
#、查询
# 、要从文件里面把所有的商品读出来
FILENAME = 'product.json'
import json
import os
def get_product():
with open(FILENAME,'a+',encoding='utf-8') as fr:
fr.seek()
content = fr.read()
if content:
res = json.loads(content)
else:
res = {}
return res
def is_price(s):
s=str(s)
if s.count('.')==:
left,right = s.split('.')
if left.isdigit() and right.isdigit():
print('正小数')
return float(s)
elif s.isdigit():
if int(s)>:
print('大于0的整数')
return int(s)
return False
def is_count(s):
if s.isdigit():
if int(s)>:
return int(s)
def write_product(product_dic):
with open(FILENAME,'w',encoding='utf-8') as fw:
json.dump(product_dic,fw,ensure_ascii=False,indent=)
def add():
all_products = get_product()
pname = input('product_name:').strip()
price = input('product_price:').strip()
count = input('product_count:').strip()
if not pname or not price or not count:#为空的时候干啥
print('不能为空!')
elif pname in all_products:
print('商品已经存在')
elif not is_price(price):
print('价格不合法,只能是大于0的数值')
elif not is_count(count):
print('数量不合法!')
else:
all_products[pname] = {"price": float(price), "count": int(count)}
write_product(all_products)
print('添加商品成功')
return
return add()
# if pname and price and count: #不为空的时候,我干啥。。
def delete():
all_products = get_product()
pname = input('product_name:').strip()
if not pname :#为空的时候干啥
print('不能为空!')
elif pname not in all_products:
print('商品不存在')
else:
all_products.pop(pname)
write_product(all_products)
print('删除商品成功')
return
return delete()
def show():
all_products = get_product()
if all_products:
print(all_products)
else:
print('暂时还没有商品!')
choice = input('1、add\n'
'2、delete\n'
'3、show \n'
'4、exit \n')
func_map = {"":add,"":delete,"":show,"":quit}
if choice in func_map:
func_map[choice]()
else:
print('输入有误!')
# if choice =="":
# add()
# elif choice=="":
# delete()
# elif choice=="":
# show()
# elif choice=="":
# quit("程序退出")
# else:
# print('输入错误!')
# def a():
# print('asdfdfs')
#
# b = a
# b()
#函数即变量