# -*- coding: utf-8 -*- """ Created on Tue Sep 11 16:35:29 2018 @author: 车路历程 """ goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998}, ] ''' 1、启动程序后,输入用户名密码后,让用户输入工资,然后打印商品列表 2、允许用户根据商品编号购买商品 3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 4、可随时退出,退出时,打印已购买商品和余额 5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示 扩展需求: 1、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买 2、允许查询之前的消费记录 ''' # 用户名为;lilu 密码为:123 # 创建的文件名称为:purchase_records.txt # 按 q键 表示退出 import re import os # 在当前目录下自动创建一个空文件purchase_records.txt desktop_path = os.getcwd() full_path = desktop_path + '\\' + 'purchase_records' + '.txt' file = open(full_path, 'a+') file.write('') file.close() name = input('请输入用户名:').strip() key = input('请输入密码:').strip() if key.isdigit(): if name == 'lilu' and key == '123': print('您上次的选购状态为:') with open('purchase_records.txt', 'r') as f: print(f.read()) with open('purchase_records.txt', 'r') as f: last_time_record_list = [i for i in f.readlines()] if len(last_time_record_list) != 0: salary = re.search("[0-9]+", last_time_record_list[-1]).group() purchase_list = re.search("[[].+[]]", last_time_record_list[-2]).group()[1:-1]\ .replace("'",'').replace(' ', '').split(",") else: purchase_list = [] salary = input('请输入您的工资:').strip() if salary.isdigit(): salary = int(salary) while True: print([(i[0], i[1]['name']) for i in enumerate(goods)]) choice = input('请根据商品编号,选择您需要的商品:').strip() if choice.isdigit() and 0 <= int(choice) < len(goods): choice = int(choice) if salary >= goods[choice]["price"]: purchase_list.append(goods[choice]["name"]) print('\033[1;31;40m%s\033[0m已加入购物车' %goods[choice]["name"]) with open('purchase_records.txt', 'a') as f: left_salary = salary - goods[choice]["price"] f.write('salary:'+str(salary)+'---'+goods[choice]["name"] +'---'+'left_salary:'+str(left_salary)+'\n') salary -= goods[choice]["price"] print('余额为:\033[1;31;40m%s\033[0m' %salary) else: print('\033[1;35;40m您的余额不足,请充值\033[0m') elif choice == 'q': print('您选择的商品为:%s'%purchase_list) with open('purchase_records.txt', 'a') as f: f.write('购买记录:%s\n'%purchase_list) f.write('账户余额:%s\n'%salary) break else: print('您输入的内容有误,请重新输入') else: print('请您输入数字') else: print('您输入的用户名和密码有误,请重新输入') else: print('请输入数字密码')