python练习---购物车

购物车
功能要求:
要求用户输入总资产,例如:2000
显示商品列表,让用户根据序号选择商品,加入购物车
购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
购买成功,打印购买的商品列表
扩展:
登录验证
 1 user_status = False
 2 def login():
 3     name_list = [
 4         {'username': '张三', 'password': '123'},
 5         {'username': '李四', 'password': '456'},
 6         {'username': '王二', 'password': '789'},
 7     ]
 8     global user_status
 9     if user_status == False:
10         username = input("请输入用户名:").strip()
11         password = input("请用户密码:").strip()
12         for i in name_list:
13             if username == i["username"] and password == i["password"]:
14                 print("login successfully")
15                 user_status = True
16                 break
17             else:
18                 print("User name or password error.")
19                 exit()
20     else:
21         print("用户已登录,验证成功")
22 
23 
24 def shopping():
25     login()
26     list_cart = []
27     goods = [{"name": "电脑", "price": 1999},
28                {"name": "鼠标", "price": 10},
29              {"name": "游艇", "price": 20},
30              {"name": "美女", "price": 998},
31     ]
32     gongzi = input("请输入您的工资:")
33     while not gongzi.isdigit():
34         print("输入内容只能由数字组成")
35         gongzi = input("输入有误,请输入正确格式:")
36     gongzi = int(gongzi)
37     while True:
38         print("商品列表".center(50, "#"))
39         print("编号".center(8, " "), "名称".center(30, " "), "价格".ljust(10, " "))
40         print("".center(53, "-"))
41         for i in goods:
42             print(str(goods.index(i)).center(10, " "), str(i["name"]).center(30, " "), str(i["price"]).ljust(10, " "))
43             print("".center(53, "-"))
44         bianhao = input("请您输入商品编号或q:")
45         if bianhao.isdigit():
46             bianhao = int(bianhao)
47             if bianhao >= 0 and bianhao < int(len(goods)):
48                 if (gongzi - goods[bianhao]["price"]) >= 0:
49                     list_cart.append(goods[bianhao])
50                     gongzi -= goods[bianhao]["price"]
51                     print("\033[32;1m您的预算还有%d\033[0m" % gongzi)
52                 else:
53                     print("\033[1;31;1m余额不足啦...\033[0m")
54             else:
55                 print("您输入的商品不存在")
56         elif bianhao == "q":
57             break
58         else:
59             print("\033[32;1m您输入有误\033[0m")
60     print("\033[32;1m还剩%d元\033[0m" % gongzi)
61     print("购物车详情".center(50,"#"))
62     print("编号".center(8, " "), "名称".center(30, " "), "价格".ljust(10, " "))
63     print("".center(53, "-"))
64     for i in list_cart:
65         print(str(list_cart.index(i)).center(10, " "), str(i["name"]).center(30, " "), str(i["price"]).ljust(10, " "))
66         print("".center(53, "-"))
67 
68 shopping()

 

posted @ 2018-04-24 21:27  飞奔的小水牛  阅读(345)  评论(0编辑  收藏  举报