管理商品demo

1、写一个管理商品的程序
# 1、商品存在文件里面
# 2、添加商品的时候,商品存在的就不能添加了,数量只能是大于0的整数,价格可以是小数、整数,但是只能是大于0的
# 商品名称
# 商品价格
# 商品数量
# 3、删除的商品的时候输入商品名称,商品不存在,要提示
# 4、修改商品的时候
# 商品名称
# 商品价格
# 商品数量
# 5、查看商品,输入商品名称,查询到商品的信息
# choice = input('请输入你的选择:'
# '1、添加商品'
# '2、删除商品'
# '3、修改商品信息'
# '4、查看商品'
# '5、退出'

import json
FILENAME='Product.json'
def read_file():
with open(FILENAME,encoding='utf-8')as fw:
return json.load(fw)
def write_file(d):
with open(FILENAME,'w',encoding='utf-8')as fw:
return json.dump(d,fw,indent=4,ensure_ascii=False)
def check_int(num):
num=str(num)
if num.isdigit() and int(num)>0:
return True
def check_price(num):
num=str(num)
if num.count('.')==1:
left,right=num.split('.')
if left.isdigit() and right.isdigit() and int(right)>0:
return True
elif check_int(num):
return True
all_product=read_file()
def add_product():
name=input('输入商品名称:').strip()
count=input('请输入数量:').strip()
price=input('请输入价格').strip()
if name and count and price:
if not check_int(count):
print('请输入正确的数量')
elif not check_price(price):
print('请输入正确的价格')
elif name in all_product:
print('商品已存在')
else:
all_product[name]={'price':price,'count':count}
write_file(all_product)
print('添加成功')
else:
print('不能为空')
def edit_product():
name=input('输入名称').strip()
while True:
if name in all_product:
break
elif name=='q':
quit('退出')
count= input('输入数量').strip()
price= input('输入价格').strip()
if name and count and price:
all_product[name] = {'price': price, 'count': count}
write_file(all_product)
print('修改成功')
else:
print('不能为空')
def del_product():
name=input('商品名称').strip()
if name not in all_product:
print('商品不存在')
else:
all_product.pop(name)
write_file(all_product)
print('删除成功')
def show_product():
while True:
name = input('商品名称').strip()
if name in all_product:
print(all_product.get(name))
break
elif name=='all':
print(json.dumps(all_product,indent=4,ensure_ascii=False))

func_map={
'1':add_product,
'2':del_product,
'3':edit_product,
'4':show_product
}
for i in range(4):
choice=input('输入你的选择\n:'
'1添加\n'
'2删除\n'
'3修改\n'
'4查看\n'
)
if choice in func_map:
func_map[choice]()
else:
print('请输入正确选项')

转载于:https://www.cnblogs.com/mzxs-jgm/p/10745565.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值