Python s12 Day2 笔记及作业 python简易购物商城

1. 元组的元素不可修改,但元组的元素的元素可以被修改。

2. name="eric"

    print(name.center(20, "*")

3. list=['a', 'b', 'c', 'd']

    str = '-'.join(list)

 4. sys.argv 处理参数

maketrans()
语法 maketrans()方法语法: str.maketrans(intab, outtab)
参数 intab
-- 字符串中要替代的字符组成的字符串。 outtab -- 相应的映射字符的字符串。
返回值 返回字符串转换后生成的新字符串。
实例 以下实例展示了使用maketrans() 方法将所有元音字母转换为指定的数字:
#!/usr/bin/python # -*- coding: UTF-8 -*- from string import maketrans # 必须调用 maketrans 函数。 intab = "aeiou" outtab = "12345" trantab = maketrans(intab, outtab) str = "this is string example....wow!!!"; print(str.translate(trantab));
以上实例输出结果如下: th3s 3s str3ng 2x1mpl2....w4w!!!

 

 

作业一:

  • 购物商城
  • 商品展示,价格
  • 买,加入购物车
  • 付款,钱不够

 

python3代码:

一共三个模块: 1. login模块负责登录  2.shopmall模块负责购物功能函数实现 3.shopcart模块为主程序

1. login

 1 import time
 2 
 3 
 4 def login():
 5     input_name = input("Please input your user name : ").strip()
 6     user_lockfile = open("user_lockfile.txt", "r+")
 7     user_file = open("user_file.txt")
 8     user_list = user_file.readlines()
 9     for i in range(3):
10         input_passwd = input("Please input your password : ").strip()
11         #查找被锁用户列表判断是否被锁住
12         if input_name in [locked_user.rstrip() for locked_user in user_lockfile.readlines()]:
13             print("Sorry, your account is locked!")
14             user_file.close()
15             user_lockfile.close()
16             exit(1)
17         else: #没有被锁住,查找用户列表
18             if input_name not in [user_record.split()[0] for user_record in user_list]:
19                 print("Sorry, your account doesn't exist!")
20                 user_file.close()
21                 user_lockfile.close()
22                 exit(2)
23             else: #用户存在,判断密码是否正确,正确跳出循环
24                 input_record = input_name + ' ' + input_passwd
25                 money = 0
26                 for user_record in user_list:
27                     user_info = user_record.split()[0]+' '+user_record.split()[1]
28                     if input_record == user_info:
29                         #money = int(user_record.split()[2])
30                         print("Logging in...")
31                         time.sleep(1)
32                         user_file.close()
33                         user_lockfile.close()
34                         return input_name
35                 else:#密码不正确,判断错误次数,错误三次(i=2)将用户锁住
36                     if i == 2:
37                         user_lockfile.write(input_name + "\n")
38                         print("Sorry, you're locked!")
39                         user_file.close()
40                         user_lockfile.close()
41                         exit(3)
42                     else:#剩余机会数 2-i
43                         chance = 2 - i
44                         print("Wrong password! %s chances left!" % chance)
45 
46 def get_money(username):
47     user_file = open("user_file.txt")
48     for line in user_file.readlines():
49         if username == line.split()[0]:
50             money = line.split()[2]
51     user_file.close()
52     return money
53 
54 def update_money(username, old, new):
55     with open("user_file.txt", 'r') as file:
56         lines = file.readlines()
57     with open("user_file.txt", 'w') as file:
58         for line in lines:
59             if line.split()[0] == username:
60                 line = line.replace(str(old), str(new))
61             file.write(line)
View Code

2. shopmall

  1 import time
  2 import homework3.login as login_module
  3 
  4 
  5 FIRST_LAYER_CHOICE = ''
  6 CART = {}
  7 USERNAME = ''
  8 CART_CHANGE_FLAG = ''
  9 
 10 def input_verify(choice):
 11     if str.isdigit(choice):
 12         choice = int(choice)
 13     return choice
 14 
 15 
 16 #欢迎界面框架
 17 def framework_show(username='', cart={}):
 18     global USERNAME
 19     USERNAME = username
 20     money = input_verify(login_module.get_money(username))
 21     print('''
 22 #############################################################
 23 *                                                           *
 24 *             Welcome to Wayne's Shopping Mall              *
 25 *                                                           *
 26 #############################################################
 27     ''', end='')
 28     userstring = "用户:%s\t余额:%d\t购物车:%d" % (username, money, len(cart))
 29     print(userstring.center(50))
 30 
 31 
 32 #商品总展示框架,一级菜单
 33 def goods_show(goods_dict):
 34     global FIRST_LAYER_CHOICE
 35     print("=============================================================")
 36     print("编号\t名称\t\t\t价格\t\t库存")
 37     print("=============================================================")
 38     for key in goods_dict.keys():
 39         name,price,inventory = goods_dict[key].values()
 40         print("%-4s\t%-12s\t%-4d\t\t%-4d" % (key, name, price, inventory))
 41     print("=============================================================")
 42     goods_input = input("请选择:\t编号(1-%d)|购物车(c)|结账(p)|退出(q) : " % max(key for key in goods_dict.keys()))
 43     goods_input = input_verify(goods_input)
 44     if goods_input == 'q':
 45         exit(0)
 46     elif goods_input == 'c' or goods_input == 'p' or goods_input in goods_dict.keys():
 47         FIRST_LAYER_CHOICE = goods_input
 48     else:
 49         print("输入错误!")
 50         FIRST_LAYER_CHOICE = ''
 51         time.sleep(2)
 52 
 53     while FIRST_LAYER_CHOICE:
 54         if FIRST_LAYER_CHOICE in goods_dict.keys():  #若选择商品编号,则调用商品信息展示函数
 55             goods_info(FIRST_LAYER_CHOICE, goods_dict)
 56         elif FIRST_LAYER_CHOICE == 'c':
 57             cart_show(goods_dict)
 58         elif FIRST_LAYER_CHOICE == 'p':
 59             pay_show()
 60 
 61 
 62 
 63 
 64 #选中商品进入二级菜单商品信息展示
 65 def goods_info(choice, goods_dict):
 66     global FIRST_LAYER_CHOICE
 67     name,price,inventory = goods_dict[choice].values()
 68     print("【编号: %s\t名称: %s\t价格: %d(元)\t库存: %d】" % (choice, name, price, inventory))
 69     if inventory == 0:
 70         print("无库存!")
 71         FIRST_LAYER_CHOICE = ''
 72         time.sleep(2)
 73     else:
 74         goods_num_input = input("请输入购买数量(库存%d)|返回(b)|退出(q): " % inventory)
 75         goods_num_input = input_verify(goods_num_input)
 76         if goods_num_input == 'q':
 77             exit(0)
 78         elif goods_num_input == 'b':  #若返回,则将全局变量赋值
 79             FIRST_LAYER_CHOICE = ''
 80         elif type(goods_num_input) is int and goods_num_input > 0 and goods_num_input <= inventory: #若输入数量在库存内
 81             add_cart(goods_dict, goods_num_input) #调用添加购物车函数
 82         else:
 83             print("输入错误!")
 84             time.sleep(1)
 85 
 86 
 87 #商品添加购物车功能实现
 88 def add_cart(goods_dict, goods_num):
 89     global FIRST_LAYER_CHOICE
 90     global CART
 91     global USERNAME
 92 
 93     name, price, inventory = goods_dict[FIRST_LAYER_CHOICE].values()
 94     confirm = input("确认购买%d个<%s>? y/n: " % (goods_num, name))
 95     if confirm == 'n':
 96         FIRST_LAYER_CHOICE = ''
 97     elif confirm == 'y':
 98         inventory = inventory - goods_num
 99         goods_dict[FIRST_LAYER_CHOICE]['inventory'] = inventory  #更新库存, 添加购物车不扣余额
100         if FIRST_LAYER_CHOICE in CART.keys(): #若购物车中存在该商品,直接修改数量,否则添加至购物车
101             CART[FIRST_LAYER_CHOICE]['num'] += goods_num
102         else:
103             CART[FIRST_LAYER_CHOICE] = {'name':name, 'price':price,'num':goods_num}
104         print("添加购物车成功!")
105         FIRST_LAYER_CHOICE = ''
106     else:
107         print("输入错误!")
108     #return cart_dict
109 
110 def cart_show(goods_dict):
111     global CART
112     global FIRST_LAYER_CHOICE
113     global CART_CHANGE_FLAG
114     print('''
115 -------------------------------------------------------------
116 *                      Shopcart                             *
117 -------------------------------------------------------------
118 编号\t物品\t\t\t单价\t\t数量''')
119     for i in sorted([i for i in CART.keys()]):
120         name = CART[i]['name']
121         price = CART[i]['price']
122         num = CART[i]['num']
123         print("%-8d%-12s\t%-4d\t\t%-4d" % (i, name, price, num))
124     print("-------------------------------------------------------------")
125     CART_CHANGE_FLAG = input("请选择  修改(c)|结账(p)|返回(b)|退出(q) : ")
126     if CART_CHANGE_FLAG == 'q': exit(0)
127     elif CART_CHANGE_FLAG == 'b':
128         FIRST_LAYER_CHOICE = ''
129     elif CART_CHANGE_FLAG == 'p':
130         pay_show()
131     elif CART_CHANGE_FLAG == 'c':
132         while CART_CHANGE_FLAG: #循环修改商品,直到用户在修改商品界面选b返回
133             cart_modify(goods_dict)
134     else:
135         print("输入错误!")
136 
137 
138 def cart_modify(goods_dict):
139     global CART
140     global FIRST_LAYER_CHOICE
141     global CART_CHANGE_FLAG
142     if CART == {}:    #若购物车为空,返回选购商品
143         print("购物车为空!请选购商品!")
144         time.sleep(1)
145         FIRST_LAYER_CHOICE = ''
146         CART_CHANGE_FLAG = ''
147     else:
148         print('''
149 -------------------------------------------------------------
150 *                      Shopcart                             *
151 -------------------------------------------------------------
152 编号\t物品\t\t\t单价\t\t数量''')
153         for i in sorted([i for i in CART.keys()]):
154             name = CART[i]['name']
155             price = CART[i]['price']
156             num = CART[i]['num']
157             print("%-8d%-12s\t%-4d\t\t%-4d" % (i, name, price, num))
158         print("-------------------------------------------------------------")
159         change_choice = input("请输入要修改的商品编号, 返回<b>: ")
160         change_choice = input_verify(change_choice)
161         if change_choice == 'b':
162             CART_CHANGE_FLAG = ''
163         else:
164             if change_choice not in CART.keys():
165                 print("输入错误!")
166             else:
167                 name, price, num = CART[change_choice].values()
168                 print("【编号: %s\t名称: %s\t价格: %d(元)\t数量: %d】" % (change_choice, name, price, num))
169                 inventory_total = goods_dict[change_choice]['inventory'] + num   #由于没付款,这里显示 总库存=当前库存+购物车数量
170                 change_num = input("请输入要购买的数量, 库存%d: " % inventory_total)
171                 change_num = input_verify(change_num)
172                 if change_num in range(1,inventory_total+1):
173                     confirm = input("确认购买%d个<%s>? y/n: " % (change_num, name))
174                     if confirm == 'y':
175                         CART[change_choice]['num'] = change_num
176                         inventory = inventory_total - change_num  #修改当前库存为 总库存-修改后的购物车数量
177                         goods_dict[change_choice]['inventory'] = inventory
178                     elif confirm == 'n':
179                         pass
180                     else:
181                         print("输入错误!")
182                 elif change_num == 0:
183                     confirm = input("确认从购物车清除<%s>? y/n: " % name)
184                     if confirm == 'y':
185                         CART.pop(change_choice) #从购物车清除后,显示当前库存为总库存
186                         goods_dict[change_choice]['inventory'] = inventory_total
187                         if CART == {}:
188                             CART_CHANGE_FLAG = ''
189                     elif confirm == 'n':
190                         pass
191                     else:
192                         print("输入错误!")
193                 else:
194                     print("输入错误!")
195 
196 
197 
198 
199 def pay_show():
200     global USERNAME
201     global CART
202     global FIRST_LAYER_CHOICE
203     if CART == {}:
204         print("购物车为空!请选购商品!")
205         time.sleep(1)
206         FIRST_LAYER_CHOICE = ''
207     else:
208         total_price = 0
209         print("*************************************************************")
210         print("%-8s%-12s%-8s%-8s" % ("编号", "商品", "数量", "总价"))
211         for i in CART.keys():
212             name = CART[i]['name']
213             num = CART[i]['num']
214             price = CART[i]['price']
215             goods_price = num * price
216             total_price += goods_price
217             print("%-10d%-14s%-10d%-4d" % (i, name, num, goods_price))
218         print("*************************************************************")
219         money = input_verify(login_module.get_money(USERNAME))
220         print("购物车总价 : %d\t|\t当前余额 : %d" % (total_price, money))
221         if money < total_price:   #若用余额不足以支付购物车,提示并返回
222             print("余额不足!请充值!")
223             time.sleep(1)
224             FIRST_LAYER_CHOICE = 'c' if FIRST_LAYER_CHOICE == 'c' else ''
225         else:
226             pay__input = input("确认购买上述物品? y/n : ")
227             if pay__input == 'y':
228                 left = money - total_price
229                 login_module.update_money(USERNAME, money, left)
230                 print("付款成功! 余额 %d 元。" % left)
231                 time.sleep(1)
232                 exit(0)
233             elif pay__input == 'n':
234                 FIRST_LAYER_CHOICE = 'c' if FIRST_LAYER_CHOICE == 'c' else ''
235             else:
236                 print("输入错误!")
237 
238 
239 def purchase(username, goods_dict):
240     while True:
241         framework_show(username)
242         goods_show(goods_dict)
View Code

3. shopcart

 1 import homework3.login as login_module
 2 import homework3.shopmall as shopmall
 3 
 4 GOODS = {1:{'name':'iphone8', 'price':6888, 'inventory':30},
 5          2:{'name':'iphoneX', 'price':8388, 'inventory':8},
 6          3:{'name':'ipad mini4', 'price':2888, 'inventory':20},
 7          4:{'name':'MI MIX2', 'price':3288, 'inventory':25},
 8          5:{'name':'MEIZU Pro8', 'price':2488, 'inventory':2}}
 9 
10 
11 if __name__ == "__main__":
12     username = login_module.login()
13     shopmall.purchase(username, GOODS)
View Code

4. 用户信息记录文件

1 wayne 123 1999829036
2 kevin 123 20000
3 root shroot123 3000

5.  用户锁定记录文件

1 kevin
2 james

 

posted on 2017-10-01 09:35  走心的狗  阅读(290)  评论(0编辑  收藏  举报

导航