|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
直接上代码 ^ - ^
- #1、添加
- #1、商品名称
- #1、要从文件里面把所有的商品读出来
- #2、价格
- #1、写一个方法判断是否为合理的价格
- #3、数量
- #整数
- # product = {
- # "爱疯差":{
- # "price":999.98,
- # "count":5
- # },
- # "car":{
- # "price":32423432,
- # "count":10
- # }
- # }
- # product['mac'] = {"price":9999,"count":5}
- # write(product)
- # 写入文件,最新的商品写进去
- #2、删除
- # 1、商品名称
- # 1、要从文件里面把所有的商品读出来
- # product = {
- # "爱疯差": {
- # "price": 999.98,
- # "count": 5
- # },
- #
- # }
- # product.pop('car')
- #3、查询
- # 1、要从文件里面把所有的商品读出来
- FILENAME = 'product.json'
- import json
- import os
- while True:
- def get_product():
- with open(FILENAME,'a+',encoding='utf-8') as fr:
- fr.seek(0)
- content = fr.read()
- if content:
- res = json.loads(content)
- else:
- res = {}
- return res
- def is_price(s):
- s=str(s)
- if s.count('.')==1:
- left,right = s.split('.')
- if left.isdigit() and right.isdigit():
- print('正小数')
- return float(s)
- elif s.isdigit():
- if int(s)>0:
- print('大于0的整数')
- return int(s)
- return False
- def is_count(s):
- if s.isdigit():
- if int(s)>0:
- 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=4)
- def add():
- all_products = get_product()
- pname = input('请输入产品名称:').strip()
- price = input('请输入产品价格:').strip()
- count = input('请输入产品数量:').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('请输入产品名称:').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、添加商品\n'
- '2、删除商品\n'
- '3、显示已有的商品 \n'
- '4、退出 \n')
- func_map = {"1":add,"2":delete,"3":show,"4":quit}
- if choice in func_map:
- func_map[choice]()
- else:
- print('输入有误!')
- # if choice =="1":
- # add()
- # elif choice=="2":
- # delete()
- # elif choice=="3":
- # show()
- # elif choice=="4":
- # quit("程序退出")
- # else:
- # print('输入错误!')
- # def a():
- # print('asdfdfs')
- #
- # b = a
- # b()
- #函数即变量
复制代码
|
|