python写购物车小程序
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # @Author: Skyell Wang # @Time : 2018/5/22 15:50 # 基础要求: # # 1、启动程序后,输入用户名密码后,让用户输入工资,然后打印商品列表 # # 2、允许用户根据商品编号购买商品 # # 3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 # # 4、可随时退出,退出时,打印已购买商品和余额 # # 5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示 # # # 扩展需求: # # 1、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买 # # 2、允许查询之前的消费记录 import re # 用户登录程序 flag = True # 剩余钱数 left_saving = True current_saving = 0 # 已有账号、密码 account_list = {'xiaopang': '123', 'haohao': '234'} username = input('请输入您的用户名:').strip() lock_name = open('lockname_list.txt', 'r', encoding="utf-8") for i in lock_name: lockname = i.strip() if lockname == username: print('您的账号已经被锁定!') break else: continue lock_name.close() if username != lockname: password_wrong = 0 while flag: password = input('请输入密码:').strip() # 利用列表生成式将账号信息存入列表中 acc_name = [keys for keys in account_list] if username in acc_name: # 判断账号、密码是否正确 if account_list[username] == password: print('欢迎回来!') flag = False # 判断与之前账号是否一致,如果一致则打印出之前的消费清单 list = open('shopping_list', 'r', encoding="utf-8") if username in [i for i in list]: with open('shopping_list', 'r', encoding="utf-8") as list: print(list.read()) left_saving = False # 取出文件中已消费后剩余金额,并将余额赋值给saving with open('shopping_list', 'r', encoding="utf-8") as list: an = [x for x in list] bc = re.findall('\d+\d', an[1]) current_saving = bc[0] list.close() break else: print('密码错误,请重新输入!') password_wrong += 1 # 密码错误3次,锁定用户 if password_wrong == 3: print('您的账号已经被锁定!') lock_name = open('lockname_list.txt', 'a+', encoding="utf-8") # 将被锁定的账号写入锁定文件中 lock_name.write(username+'\n') lock_name.close() else: print('该账号不存在') flag = False break # 购物车程序 product_list=[ ('电脑', 1999), ('鼠标', 10), ('游艇', 20), ('美女', 998), ('房子', 8000), ] if left_saving: saving = input('请输入您的工资:') else: saving = str(current_saving) shopping_car = [] if saving.isdigit(): saving = int(saving) while True: # 打印商品内容 for i, v in enumerate(product_list, 1): print(i, '>>>>', v) # 引导用户选择商品 choice = input('选择购买商品编号[退出:q]:') # 验证输入是否合法 if choice.isdigit(): choice = int(choice) if choice > 0 and choice <= len(product_list): # 将用户选择商品通过choice取出来 p_item = product_list[choice-1] # 如果钱够,用本金saving减去该商品价格,并将该商品加入购物车 if p_item[1] < saving: saving -= p_item[1] shopping_car.append(p_item) else: print('\033[1;31;0m') print('余额不足,还剩%s元'%saving) print('\033[0m') print(p_item) else: print('编码不存在') elif choice == 'q': print('\033[1;34;0m') print('------------您已经购买如下商品----------------') print('\033[0m') # 循环遍历购物车里的商品,购物车存放的是已买商品 buy_list=[i for i in shopping_car] print(buy_list) # 将购买物品信息存入文件中 with open('shopping_list','w', encoding = "utf-8") as list: list.write(str(buy_list)+'\n'+'您还剩:%s元钱' % saving + '\n' + username) # 高亮显示所剩余额 print('\033[1;34;0m') print('您还剩:%s元钱' % saving) print('\033[0m') break else: print('invalid input')
数据驱动变革-云将skyell。用Flask+Nginx+uWsgi搭建的个人博客:http://www.skyell.cn/