python编写商品管理,python编写商品,# 1、实现


#     1、实现一个商品管理的程序。
# #输出1,添加商品 2、删除商品 3、查看商品
# 添加商品:
# 商品的名称:xxx 商品如果已经存在的话,提示商品商品已经存在
# 商品的价格:xxxx 数量只能为大于0的整数
# 商品的数量:xxx,数量只能为大于0的整数
# 2、删除商品:
# 输入商品名称:
# iphone 如果输入的商品名称不存在,要提示不存在
# 3、查看商品信息:
# 输入商品名称:
# iphone:
# 价格:xxx
# 数量是:xxx
# all:
# print出所有的商品信息
import json
def add_product():
product = input(‘请输入商品名称:‘).strip()
count = input(‘请输入商品数量:‘).strip()
price = input(‘请输入商品价格:‘).strip()
f = open(‘product.json‘, ‘a+‘, encoding=‘utf-8‘)
f.seek(0)
products = json.load(f)
if product == ‘‘:
print(‘商品名称不能为空‘)
elif product in products:
print(‘商品已存在‘)
elif not count.isdigit():
print(‘商品数量必须为正整数‘)
elif not price.isdigit():
print(‘商品价格必须为正整数‘)
else:
products[product] = {}
products[product][‘count‘] = int(count)
products[product][‘price‘] = int(price)
f.seek(0)
f.truncate()
json.dump(products, f, indent=4, ensure_ascii=False)
f.close()

def show_product(product):
f = open(‘product.json‘, encoding=‘utf-8‘)
products = json.load(f)
f.close()
if (product==‘all‘):
return products
elif not (product in products):
print(‘商品不存在‘)
else:
#print(products[product])
return product+‘:\n 数量:‘+str(products[product][‘count‘])+‘\n 价格:‘+str(products[product][‘price‘])

def del_product(product):
f = open(‘product.json‘, ‘a+‘, encoding=‘utf-8‘)
f.seek(0)
products = json.load(f)
if not (product in products):
print(‘商品不存在‘)
else:
del products[product]
f.seek(0)
f.truncate()
json.dump(products, f, indent=4, ensure_ascii=False)
f.close()

print("输出1、添加商品 2、删除商品 3、查看所有商品")
choice=input()
if choice=="1":
add_product()
elif choice=="2":
product=input(‘请输入要删除的商品名称:‘)
del_product(product)
elif choice=="3":
product=input(‘请输入要查询的商品名称:‘)
print(show_product(product))
else:
print(‘输入有误‘)

python编写商品管理

评论关闭