import time import os goods = [ {"name": "电脑", "price": 100}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 1000}, {"name": "美女", "price": 1}, ] shopping_cart = [] _username = "alex" _password = "123" count = 0 while count < 3:#用户名密码循环1 username = input("\033[1;32m请输入用户名:\033[0m").strip() password = input("\033[1;32m请输入密码:\033[0m").strip() if username == _username and password == _password: print("\033[1;34m-----登录成功,欢迎%s\033[0m" % username) #得到工资 with open("salary", 'r') as f1: data = f1.read() if data: salary = float(data) print("\033[1;31m你的余额还有:%s\033[0m" % salary) else: while True:#工资循环2 salary = input("\033[1;32m请输入你的工资:\033[0m").strip() if salary.isdigit():#只能够吧3456转换,不能转换3456.444, salary = float(salary) break else: print("输入有误,重新输入") while True: #商品列表循环3 print("————————商品列表——————————") for index, item in enumerate(goods): print("%s %s %s "%(index,item["name"], item["price"])) choice = input("\033[1;34m输入要买的商品编号|查看消费记录b|退出q:\033[0m").strip() if choice.isdigit(): choice = int(choice) if choice < len(goods): if salary >= float(goods[choice]["price"]): shopping_cart.append([goods[choice]["name"],goods[choice]["price"]])\ #消费记录加入文件 with open("shopping_records", 'a') as f: now_time = time.ctime() goods_choice = [goods[choice]["name"],goods[choice]["price"]] records = str(now_time) + "\t" + str(goods_choice) + "\n" f.write(records) print("\033[1;32m>你购买了%s\033[0m"%goods[choice]["name"]) salary -= float(goods[choice]["price"]) print("\033[1;31m>余额剩余%s\033[0m"%salary) else: print("033[1;31m余额不足,请重新选择\033[0m") else: print("\033[1;31m你输入的商品不存在\033[0m") elif choice == "b": with open("shopping_records", 'r')as f: records = f.read() if len(records): print("——————消费记录——————") print(records) else: print("\033[1;31m>>你还没用买过东西\033[0m") elif choice == "q": if len(shopping_cart) > 0: print("\033[1;32m_____你的购物车————————") for index , item in enumerate(shopping_cart): print(index,item[0],item[-1]) print("——————————————————————————") print("你的余额:%s\033[0m"%salary) with open("salary", "w")as f2: f2.write(str(salary)) exit() else: print("\033[1;31m你的购物车为空,你的余额:%s\033[0m"%salary) with open("salary", "w") as f2: f2.write(str(salary)) exit() else: print("\033[1;31;47m你输入有误,重新输入\033[0m") else: print("\033[1;31;47m用户名或者密码错误\033[0m") count += 1 print("you have try more times")