python习题:用文件方式编写购物车程序,添加,查看和删除

#2、写一个添加商品的程序    必做
# 1、添加商品
#商品名称
#价格
#数量
#颜色
# 2、查看商品
# 3、删除商品
#输入商品名称


PRODUCT_FILE='products' # 大写变量名称的代表 常量

def op_file(filename,content=None):
f = open(filename,'a+',encoding='utf-8')
f.seek(0)
if content!=None:
f.truncate()
f.write(str(content))
f.flush()
else:
res = f.read()
if res:
products = eval(res)
else:
products = {}
return products
f.close()

def check_price(s):# 100
s = str(s)
if s.count('.') == 1:
s_list = s.split('.') #[1,5] [-s,55]
left = s_list[0] # -s ['','s']
right = s_list[1]
if left.isdigit() and right.isdigit(): #正小数
return True
elif s.isdigit() and int(s)>0:#整数
return True
return False

def check_count(count):
if count.isdigit():
if int(count)>0:
return True
return False

def add_product():
while True:
name = input('name:').strip()
price = input('price:').strip()
count = input('count:').strip()
color = input('color:').strip()
if name and price and count and color:
products = op_file(PRODUCT_FILE)
if name in products:
print('商品已经存在')
elif not check_price(price): #价格不合法,价格不合法Fasle
print('价格不合法')
elif not check_count(count):#数量不合法
print('商品数量不合法!')
else:
product = {'color':color,'price':'%.2f'%float(price),'count':count}
products[name]=product
op_file(PRODUCT_FILE,products)
print('商品添加成功!')
break
else:
print('必填参数未填!')


def view_products():
products = op_file(PRODUCT_FILE)
if products:
for k in products:
print('商品名称【%s】,商品信息【%s】'%(k,products.get(k)))
else:
print('当前没有商品')

def del_product():
while True:
name = input('name:').strip()
if name:
products = op_file(PRODUCT_FILE)
if products:
if name in products:
products.pop(name)
op_file(PRODUCT_FILE,products)
print('删除成功!')
break
else:
print('你输入的商品名称不存在,请重新输入!')
else:
quit('当前没有商品!')

else:
print('必填参数未填!')

def start():
choice = input('请输入你的选择:1、添加商品 2、查看商品 3、删除商品,q退出:').strip()
if choice == '1':
add_product()
elif choice=='2':
view_products()
elif choice=='3':
del_product()
elif choice=='q':
quit('谢谢光临')
else:
print('输入错误!')
return start()

start()