完成文件解析,再進行購物車作業
f = open('Fileshopping','w',encoding='utf-8')
f.write('電腦 1999\n鼠標 10\n遊艇 20\n美女 998\n')
f.close()
f = open('Fileshopping',encoding='utf-8')
shop_list = []
for line in f:
shop_dict = {'name': None, 'price': None}
# line = line.strip() # 沒用的嗎
if line.strip():
list1 = line.split()
shop_dict['name'] = list1[0]
shop_dict['price'] = list1[1]
shop_list.append(shop_dict)
f.close()
# print(shop_list) # 不用的
shopping_list = []
l = []
total = input('請輸入你所有的錢:')
while True:
if total.isdigit():
if int(total) > 10:
for i in range(1,5):
if int(total) >= int(shop_list[i-1]['price']):
print(i,shop_list[i-1]['name'],shop_list[i-1]['price'])
l.append(i)
choice = input('請輸入要選擇的商品的序號:')
if choice.isdigit():
choice = int(choice)
# if l.find(choice+1) != -1:
if choice <= 4:
if int(total) >= int(shop_list[choice - 1]['price']):
total = int(total) - int(shop_list[choice - 1]['price'])
shopping_list.append(shop_list[choice - 1]['name'])
print(shop_list[choice - 1]['name'],'已加入購物車,您還剩',total,'元錢')
total = str(total)
elif int(total) < int(shop_list[choice - 1]['price']):
print('餘額不足,請選購以下商品:')
else:
print('請重新輸入正確數字序號')
else:
print('請重新輸入正確數字序號')
elif choice.upper() == 'Q':
break
else:
print('請輸入正確指令')
else:
print('餘額不足啦,已自動爲你退出')
break
elif total.upper() == 'Q':
break
else:
print('請輸入正確指令')
print('您已經購買:',shopping_list)