购物车程序
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/3/6 21:01 # @Author : hyang # @Site : # @File : shop_cart.py # @Software: PyCharm """ 购物车程序 数据结构: goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998}, ...... ] 功能要求: 基础要求: 1、启动程序后,输入用户名密码后,让用户输入工资,然后打印商品列表 2、允许用户根据商品编号购买商品 3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 4、可随时退出,退出时,打印已购买商品和余额 5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示 扩展需求: 1、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买 2、允许查询之前的消费记录 """ import os # 商品列表 goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "IPAD", "price": 1998}, {"name": "手机", "price": 998}, {"name": "玩具", "price": 50}, {"name": "教科书", "price": 100} ] last_shop = [] # 上次购买数据 last_bal = [] # 得到每次购买余额 def is_shop(user): """ 判断该用户是否已消费数据 :param user: :return: """ flg = False if os.path.exists(r"user_shop.txt"): # 查询用户有购买记录 with open(r"user_shop.txt", "r", encoding='utf-8') as f: for line in f: if line.find(user) != -1: flg = True break else: # 创建空文件 with open(r"user_shop.txt", "w", encoding='utf-8') as f: f.write("") return flg def login(): """ 用户登录 :return: """ err_cnt = 0 suc_user = '' # 返回成功登录用户 # 判断锁标志 while err_cnt < 3: user = input('输入用户名: ') pwd = input('输入密码: ') if user == 'alex' and pwd == '123': print('登录成功') suc_user = user break else: print('登录失败') err_cnt += 1 else: print('您登录失败已超过3次') return suc_user def check_salary(): """ 检查收入 :return: """ while True: salary = input('输入工资: ') if salary.isdigit(): break else: print('工资输入错误,请重新输入!') return int(salary) def shop(user, salary): """ 用户购物 """ shop_cart = [] # 购物车 while True: print('-------商品列表--------') for index, value in enumerate(goods): print('商品编号:%s 商品名称:%s 商品价格:%s' % (index, value['name'], value['price'])) choice = input('输入商品编号:---输入q退出购买 ') if choice.isdigit(): choice = int(choice) if 0 <= choice < len(goods): price = goods[choice]['price'] if (salary - price) > 0: salary = salary - price shop_cart.append(goods[choice]) print('