python作業/練習/實戰:3、實現商品管理的一個程序
阿新 • • 發佈:2018-09-06
pan utf python文件 學習筆記 要求 span 定義 add utf-8
作業要求
實現一個商品管理的一個程序,
運行程序有三個選項,輸入1添加商品;輸入2刪除商品;輸入3 查看商品信息
1、添加商品:
商品名稱:xx 商品如果已經存在,提示商品已存在
商品價格:xx數量只能為大於0的整數
商品數量:xx,數量只能是大於0的整數
2、刪除商品:
輸入商品名稱 ,就把商品刪掉
輸入輸入的商品名稱不存在,要提示不存在
3、查看所有的商品
輸入商品名稱,查出對應價格、數量
輸入all 打印出所有的商品信息
輸入的商品不存在提示商品不存在
提示
def函數、文件操作、json與字典的轉換
相關教程
python學習筆記(四):python文件操作
python學習筆記(五):python中json與字典格式轉換
python學習筆記(六):函數--def自定義函數
代碼範例
product_file = ‘product_file.json‘ import json # 讀取文件並轉換成字典 def read_goods(): with open(product_file,‘a+‘,encoding=‘utf-8‘) as f:#打開文件 f.seek(0) contend=f.read()#讀取文件 if len(contend):#判斷長度的 if不為空rf=json.loads(contend) # 這裏必須取出數據轉成dict格式 否則後續添加商品有問題 return rf else: return {} # 增加商品 def add_good(): good=input(‘請輸入商品名稱:‘).strip() count=input(‘請輸入商品數量:‘).strip() price=input(‘請輸入商品價格:‘).strip() all=read_goods() ifgood==‘‘: print(‘商品名稱不能為空‘) elif good in all: print(‘商品已經存在‘) elif int(count)<=0: print(‘商品數量為大於0的整數‘) elif int(price)<=0: print(‘商品價格為大於0的整數‘) else: all[good]={‘price‘:price,‘count‘:count}#將商品加入到字典中 with open (product_file,‘w‘,encoding=‘utf-8‘) as f: #寫操作 json.dump(all,f,indent=4,ensure_ascii=False)# 這句代碼牛牛再講一下吧 # 查看商品 def show_good(): all=read_goods() s_good=input(‘請輸入要查看的商品名稱‘).strip() if s_good in all: s_price=all[s_good][‘price‘] s_count=all[s_good][‘count‘] print(‘商品名稱:%s\n商品價格:%s\n商品數量:%s‘%(s_good,s_price,s_count)) elif s_good==‘all‘: print(all) # 刪除商品 def del_good(): all=read_goods() d_good=input(‘請輸入要刪除的商品名稱:‘).strip() if d_good in all: all.pop(d_good) with open(product_file,‘w‘,encoding=‘utf-8‘)as f: json.dump(all,f,indent=4,ensure_ascii=False) print(‘已將商品 %s 成功刪除‘%d_good) choice=input(‘請選擇您的操作:\n1、添加商品\n2、刪除商品\n3、查看商品‘) if choice==‘1‘: add_good() elif choice==‘2‘: del_good() elif choice==‘3‘: show_good() else: print(‘輸入有誤‘)
python作業/練習/實戰:3、實現商品管理的一個程序