1. 程式人生 > >一個可以添加商品、查詢商品的程序,登錄成功的話,再去操作,添加、查詢商品,添加商品也是寫在文件裏面

一個可以添加商品、查詢商品的程序,登錄成功的話,再去操作,添加、查詢商品,添加商品也是寫在文件裏面

指定 true rod 成功 文件 font split digi 邏輯

#寫一個可以添加商品、查詢商品的這麽程序
#1、先登錄,登錄的用戶名和密碼都是寫在文件裏面的
#1、讀文件、字符串分割
#2、登錄成功的話,再去操作,添加、查詢商品,添加商品也是寫在文件裏面
#1、讀寫文件,
# 字典添加元素,取元素,
# str()強制類型轉換,
# eval()#用它把字符串轉成字典
‘‘‘
{
‘mac‘:{
‘id‘:1,
‘price‘:2222.22
},
‘iphone‘:{
‘id‘:2,
‘price‘:22222
}
}

{
‘mac‘:{
‘id‘:1,
‘price‘:2222.22
},
‘iphone‘:{
‘id‘:2,
‘price‘:22222
},
‘shubao‘:{
}
}

‘‘‘
#int()
#float()
#str()
#list()
#tulpe()
#dict()


#下面這一段是登錄的邏輯

#字典取值是最方便的
all_users = {}#用來存放所有的用戶名和密碼
login_tag = False #標示是否登錄
with open(‘users‘) as fr:
for line in fr:
up = line.strip().split(‘,‘) #分隔賬號密碼
# print(‘分隔完之後的賬號密碼‘,up)
s_username = up[0]#賬號
s_pwd = up[1]#密碼
all_users[s_username]=s_pwd#把賬號作為key,密碼作為value放到用戶的字典裏
# print(all_users)
print(‘歡迎登錄白羊座商品管理系統‘.center(50,‘*‘))
username = input(‘輸入賬號:‘).strip()
pwd = input(‘輸入密碼:‘).strip()
if username in all_users:
if all_users[username]==pwd:#登錄成功
login_tag = True
else:
print(‘密碼不對!‘)
else:
print(‘用戶不存在‘)

#下面這一段是操作商品的
if login_tag:
#判斷是否登錄
while True:
choice = input(‘1添加商品,2查詢商品,3退出,請輸入你的選擇:‘).strip()
fp = open(‘products.txt‘, ‘a+‘)
fp.seek(0)
products_str = fp.read()
# 這個是從文件裏面讀出來商品信息,是字符串
if len(products_str):
# 這裏是判斷文件內容是否為空的,如果不為空的話,長度就大於0,就是真
# 一旦走這就說明是有產品
products_dic = eval(products_str)
# 是把讀出來商品信息轉成字典
else:
# 走這裏就說明是沒有商品信息的
products_dic = {} # 存放所有的商品
if choice == ‘1‘:#添加商品
p_name = input(‘請輸入商品名稱:‘).strip()
p_id = input(‘請輸入商品id:‘).strip()
p_price = input(‘請輸入商品價格:‘).strip()
if p_name!=‘‘ and p_id !=‘‘ and p_price!=‘‘:
#if和elif都是條件為真的時候才走的
if p_name in products_dic:
print(‘商品已存在!‘)
elif not p_price.isdigit():
#not True是flase,指定走不到這裏
#not Flase,就是true,就走這了
print(‘商品價格不合法!‘)
else:
products_dic[p_name]={‘id‘:p_id,‘price‘:p_price}
#products是存最新所有商品,給這個字典添加商品
fp.seek(0)
#因為上面讀完之後文件指針到最後了,所以需要移動到最前面
fp.truncate()
#清空文件
fp.write(str(products_dic))
print(‘商品添加成功‘)
else:
print(‘商品名稱、商品id、商品價格都不能為空‘)

elif choice == ‘2‘:
p_name = input(‘請輸入你要查詢的商品名稱:‘).strip()
if p_name in products_dic:
p_id = products_dic[p_name][‘id‘]
p_price = products_dic[p_name][‘price‘]
print(‘商品名稱是:【%s】,商品id是【%s】,商品價格是【%s】‘%(p_name,p_id,p_price))
else:
print(‘你輸入的商品不存在!‘)
elif choice==‘3‘:
fp.close()
exit(‘程序退出!‘)

else:
print(‘請輸入1-3的選項!‘)

else:
print(‘未登錄,沒有權限做操作‘)

一個可以添加商品、查詢商品的程序,登錄成功的話,再去操作,添加、查詢商品,添加商品也是寫在文件裏面