1 # -*- coding: utf-8 -*- 2 """ 3 基础需求: 4 1.启动程序后,输入用户名密码后 让用户输入工资 然后打印商品列表 5 2.允许用户根据商品编号购买商品 6 3.用户选择商品后 检测余额是否够 够就直接扣款 不够就提醒 7 4.可随时退出 退出时 打印已够买得商品和余额 8 5.在用户的使用过程中 关键书输出 如余额 商品已加入购物车等消息 需高亮显示 9 """ 10 goods = [ 11 {"name": "电脑", "price": 1999}, 12 {"name": "鼠标", "price": 10}, 13 {"name": "游艇", "price": 20}, 14 {"name": "美女", "price": 998} 15 ] 16 _username = "alice" 17 _password = "123" 18 buy_goods = [] 19 20 while True: 21 username = input("请输入用户名(输入q表示退出):") 22 if username == "q": 23 break 24 password = input("请输入密码(输入q表示退出):") 25 if password == "q": 26 break 27 if not username and not password: continue 28 if username == _username and password == _password: 29 while True: 30 prize = input("请输入工资(输入q表示退出):") 31 temp = prize.split('.') 32 if not prize: continue 33 if prize.isdigit(): 34 prize = int(prize) 35 elif len(temp) == 2 and temp[0].isdigit() and temp[1].isdigit(): # 判断输入的工资是小数 36 prize = float(prize) 37 elif prize == "q": 38 exit() 39 else: 40 print("-----工资输入有误,请重新输入!-----") 41 continue 42 for index, i in enumerate(goods): 43 print("%s.%s %d" % (index, i["name"], i["price"])) 44 while True: 45 num = input("请输入编号,购买商品(输入q表示退出):") 46 if not num: continue 47 if num.isdigit(): 48 num = int(num) 49 if num < len(goods): 50 if goods[num]["price"] < prize: 51 prize -= goods[num]["price"] 52 buy_goods.append(goods[num]) 53 print("-----商品 33[1;35;46m %s 33[0m 已加入购物车!-----" % goods[num]["name"]) 54 else: 55 print("-----您得余额不够,请够买其他商品!-----") 56 else: 57 print("-----输入得编号不在商品范围内,请重新输入!-----") 58 elif num == 'q': 59 print("-----您的余额: 33[1;31;47m %d 33[0m -----" % prize) 60 print("您购买了 %d 件商品:" % (len(buy_goods))) 61 for index, i in enumerate(buy_goods, 1): 62 print("%d.%s %d" % (index, i["name"], i["price"])) 63 exit() 64 else: 65 print("-----输入编号有误,请重新输入!-----") 66 else: 67 print("-----用户名或密码有误,请重新输入!-----")