python編寫商品管理

來源:互聯網
上載者:User

標籤:import   enc   程式   else   close   str   正整數   sci   ensure   

#     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編寫商品管理

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.