# coding=utf-8 #Author:yang product_list = { '1':['Iphone',5800], '2':['Mac Pro',9800], '3':['Bike',800], '4':['Watch',10600], '5':['Coffee',31], '6':['Alex Python',120], } def shopping():#定义shopping函数, with open('records','r') as f: name_list = f.read()#读取文件 if name_list == '':#如果文件为空,给name_list赋值为{} name_list = {} return name_list else:#不为空,将文件里内容转化为字典,返回name_list name_list = eval(name_list) return name_list name_list = shopping()#调用shopping函数 while True: name = input("请输入用户名(按q退出程序):") if name == 'q':#输入q退出程序 break else:#输入其他值,请用户输入密码 password =input("请输入密码:") if name not in name_list:#输入用户不在records文件里,输入工资 salary = input("请输入工资:") shopping_list = [] if salary.isdigit():#将输入的数字转换为int类型 salary = int(salary) else: shopping_list = name_list[name][1]#用户存在于records文件内,直接调用清单 print('您上次购物的清单为:%s' % shopping_list) salary = name_list[name][0]#调用剩余金额 balance = input("是否查询账户余额(Y/N):")#是否查询余额 if balance == 'Y': print('您上次所剩余额为:%s' % salary) else: pass while True: for k,v in product_list.items():#打印货物清单 print(k,v) choise = input("请输入你要买的商品编号(按q返回登录界面):") if choise.isdigit():#将输入的数字转换为int类型 goods = product_list[choise][0] value = product_list[choise][1] choise = int(choise) if choise <= len(product_list) and choise >0: #当输入的数字在范围内 shopping_list.append(goods) #添加到购物车 if value <= salary: #判断价格是否大于工资 salary -= value #大于就减少工资 print('购买成功,您所购买的商品为%s,所剩下的余额为\033[51;1m%s\033[0m\n' % (goods,salary)) else: print('\033[21;1m你的钱不够,请选择其他商品。\033[0m\n') else: print('请输入商品编号!(按q返回登录界面)') elif choise == 'q':#输入q打印商品名称,将清单添加到records文件中,返回登陆界面。 print('以下是您买的商品' ) name_list[name] = [salary, []] for i in shopping_list: name_list[name][1].append(i) print(i) with open('records','w+') as d: d.write(str(name_list)) break else: print('请输入商品编号!(按q返回登录界面)')