Python3学习笔记5:字符串操作、dict字典的合理使用-
学习Python3,坚持每一次学习都有一点点知识的积累,瞄准目标gogogo!这次仍然是练习,增加字符串操作、dict字典的合理使用,使用了一些稍微复杂的逻辑(题目源自老男孩)
购物车程序商家入口:
可以增加商品;
修改商品。
先上代码:
#Author wsp ##商家程序,要求如下: #可以添加商品,修改商品价格 print("这里是商品后台系统".center(70, "#")) while True: #只读方式打开文件 goods_file_r = open("goods.txt", "r") lines = goods_file_r.readlines() #涉及到去重,使用字典 goods_list = {} print("当前商品列表如下:") for line in lines: goods_line = line.split(" ") if goods_line.__len__() == 2: goods_list[goods_line[0].strip()] = goods_line[1].strip() print("{name} {cost}".format(name=goods_line[0].strip(), cost=goods_line[1].strip())) #关闭文件句柄 goods_file_r.close() choice = input("商品信息显示完成,请选择操作,1-》增加商品;2-》修改商品:") if choice.isdigit(): choice = int(choice) ##增加商品 if choice == 1: new_goods_name = input("请输入要增加的商品名:") if len(new_goods_name) != 0 and not goods_list.__contains__("new_goods_name"): while True: new_goods_cost = input("请输入商品价格:") if new_goods_cost.isdigit(): new_goods_cost = int(new_goods_cost) goods_list[new_goods_name] = new_goods_cost #写的方式打开文件 goods_file_w = open("goods.txt", "w") for goods_new in goods_list: line = "{name} {cost} ".format(name=goods_new, cost=goods_list[goods_new]) goods_file_w.write(line) #1goods_file.write(" ") print("增加商品{name},金额为{cost}".format(name=new_goods_name, cost=new_goods_cost)) #关闭写文件句柄 goods_file_w.close() break else: print("请输入正确的价格") continue else: print("请输入正确的商品名称") #修改商品 elif choice == 2: new_goods_name = input("请输入要修改的商品名:") if goods_list.__contains__(new_goods_name): while True: new_goods_cost = input("请输入商品价格:") if new_goods_cost.isdigit(): new_goods_cost = int(new_goods_cost) goods_list[new_goods_name] = new_goods_cost # 写的方式打开文件 goods_file_w = open("goods.txt", "w") for goods_new in goods_list: goods_file_w.writelines("{name} {cost}".format(name=goods_new, cost=goods_list[goods_new])) goods_file_w.write(" ") goods_file_w.close() break else: print("请输入正确的价格") continue else: print("商品{new_goods_name}不存在请输入正确的商品名称".format(new_goods_name=new_goods_name)) else: print("请输入正确的数字!")