作業要求
實現一個商品管理的一個程序,
運行程序有三個選項,輸入1添加商品;輸入2刪除商品;輸入3 查看商品信息
1、添加商品:
商品名稱:xx 商品如果已經存在,提示商品已存在
商品價格:xx數量只能為大於0的整數
商品數量:xx,數量只能是大於0的整數
2、刪除商品:
輸入商品名稱 ,就把商品刪掉
輸入輸入的商品名稱不存在,要提示不存在
3、查看所有的商品
輸入商品名稱,查出對應價格、數量
輸入all 打印出所有的商品信息
輸入的商品不存在提示商品不存在
提示
def函數、文件操作、json與字典的轉換
相關教程
python學習筆記(五):python中json與字典格式轉換
代碼范例
# 定義一個變量,最好用大寫字母,表示它是一個常量,不會改變 product_file = 'product_file.json' import json # 定義一個公共函數,獲取文件內容並轉換成字典,共后面三個調用 def read_goods(): with open(product_file,encoding='utf-8') as f:#讀取文件 contend=f.read()#讀取文件 if len(contend)>0:#判斷文件不為空 # if contend:#這兩種寫法都可以,因為非空即真 rf=json.loads(contend) # json轉化成字典 else: rf= {} # 否則返回一個空字典,說明文件里沒東西 return rf # 增加和刪除都是寫文件,定義一個函數,供他們倆使用 def write_file_comtent(dic): with open (product_file,'w',encoding='utf-8') as f : json.dump(dic,f,indent=4,ensure_ascii=False)#空四格,中文要顯示 #判斷是否為int類型和是否>0,供增加商品使用 def check_digit(st:str): #告訴他傳過來的是str類型 if st.isdigit():# 判斷是否為整數 st=int(st) if st>0:# 再判斷是否大於0 return st else: return 0 else: return 0 # 增加商品 def add_good(): good=input('請輸入商品名稱:').strip() count=input('請輸入商品數量:').strip() price=input('請輸入商品價格:').strip() all=read_goods() #獲取全部內容 if good=='': print('商品名稱不能為空') elif good in all: print('商品已經存在') elif check_digit(count)==0: print('商品數量為大於0的整數') elif check_digit(price)==0: print('商品價格為大於0的整數') else: all[good]={'price':int(price),'count':int(count)}#將商品加入到字典中,添加一個key和他的值 write_file_comtent(all) # 調用函數,寫入文件中 # 查看商品 def show_good(): s_good=input('請輸入要查看的商品名稱').strip() all=read_goods() if s_good=='all': print(all) elif s_good not in all: print('商品不存在') else: print(all.get(s_good)) # 刪除商品 def del_good(): d_good=input('請輸入要刪除的商品名稱:').strip() if d_good in all: all.pop(d_good) print('已將商品 %s 成功刪除'%d_good) write_file_comtent(all) # 調用函數,將字典寫入文件中 choice=input('請選擇您的操作:\n1、添加商品\n2、刪除商品\n3、查看商品') if choice=='1': add_good() elif choice=='2': del_good() elif choice=='3': show_good() else: print('輸入有誤')