python小练习-商品管理小程序

#需求:1、添加商品 包括名称、价格数量2、查看商品信息3、删除、4、修改5退出6操作文件
import json
file_name='goods.json'
def opfile(name,content=None):
 if content:
  with open(name,'w',encoding='utf8')as fw:
   json.dump(content,fw,indent=4)
 else:
  with open(name,encoding='utf8')as fr:
   res=json.load(fr)
   return res
all_goods = opfile('goods.json')
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('.')
   left = tmp[0]
   right = tmp[1]
   if left.isdigit() and right.isdigit() and int(left) >0:
    return True
   elif left.isdigit() and right.isdigit() and int(right) >0:
    return True
  return False

def get_goodsinfo():
 while True:
  good_name = input("商品名称:").strip()
  price = input("商品价格:").strip()
  count = input("商品数量:").strip()
  color = input("商品颜色:").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('数量不合法,必须是大于0的整数')
   else:
    return good_name,price,count,color
  else:
   print("输入不能为空")
def add_goods():
 good_name,price,count,color = get_goodsinfo()
 if good_name not in all_goods:
  all_goods[good_name]={
   'price':price,
   'count':count,
   'color':color
  }
  opfile(file_name,all_goods)
  print('商品添加完成')
 else:
  print('商品已经存在')

def update_goods():
 good_name,price,count,color = get_goodsinfo()
 if good_name in all_goods:
  all_goods[good_name]={
   'price':price,
   'count':count,
   'color':color
  }
  opfile(file_name,all_goods)
  print('商品修改完成')
 else:
  print('商品不存在')


def query_goods():
 good_name = input('商品名称:').strip()
 if good_name in all_goods:
  print(all_goods.get(good_name))
 else:
  print("商品不存在")
def delete_goods():
 good_name = input('商品名称:').strip()
 if good_name in all_goods:
  all_goods.pop(good_name)
  opfile(file_name,all_goods)
 else:
  print("商品不存在")
def main():
 for i in range(3):
  choice = input('请输入你的选择'
     '1:添加'
     '2:修改'
     '3:删除'
     '4:查看'
     '5:退出')
  if choice=='1':
   add_goods()
  elif choice=='2':
   update_goods()
  elif choice=='3':
   delete_goods()
  elif choice=='4':
   query_goods()
  elif  choice=='5':
   quit('程序退出')
  else:
   print("输入错误,请重新输入")
   return main()
main()

转载于:https://www.cnblogs.com/morning1/p/9238445.html

你可能感兴趣的:(python小练习-商品管理小程序)