完成文件解析,再进行购物车作业
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)