基础知识练习

1、logger配置

 1 """
 2 logging配置
 3 """
 4 
 5 import logging.config
 6 import logging
 7 
 8 # 定义三种日志输出格式 开始
 9 
10 standard_format = '[task_id:%(name)s][%(asctime)s][%(threadName)s:%(thread)d][%(filename)s:%(lineno)d]' \
11                   '[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字
12 
13 simple_format = '[task_id:%(name)s][%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
14 
15 id_simple_format = '[task_id:%(name)s][%(levelname)s][%(asctime)s] %(message)s'
16 
17 
18 #定义日志文件的路径
19 LOG_PATH=r'a3.log'
20 BOSS_LOG_PATH=r'boss.log'
21 # log配置字典(字典的key不能改)
22 LOGGING_DIC = {
23     'version': 1, #定义的版本
24     'disable_existing_loggers': False,#无用
25 
26     #1、定义日志的格式
27     'formatters': {#字典的key可以随便取
28         'standard': {#key是固定格式
29             'format': standard_format#定义的日志格式
30         },
31         'simple': {
32             'format': simple_format
33         },
34         'id_simple':{
35             'format':id_simple_format
36         },
37     },
38     'filters': {},   #过滤,不用
39 
40     #2、定义日志输入的目标:文件或者终端
41     'handlers': {#控制文件写入
42         #打印到终端的日志
43         'stream': {
44             'level': 'DEBUG',
45             'class': 'logging.StreamHandler',  # 打印到屏幕
46             'formatter': 'simple'#绑定格式
47         },
48         #打印到文件的日志,收集info及以上的日志
49         'access': {
50             'level': 'DEBUG',
51             'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件(日志轮转)
52             'formatter': 'standard',#绑定日志格式
53             'filename': LOG_PATH,  # 日志文件
54             'maxBytes': 1024*1024*5,  # 日志大小 5M#一份日志文件的大小
55             'backupCount': 5,#最多保存五份日志,写完五份时轮转
56             'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
57         },
58         #打印到文件的日志,收集info及以上的日志,为bosss设置的日志
59         'boss': {
60             'level': 'ERROR',
61             'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件(日志轮转)
62             'formatter': 'id_simple',#绑定日志格式
63             'filename': BOSS_LOG_PATH,  # 日志文件
64             'maxBytes': 1024*1024*5,  # 日志大小 5M#一份日志文件的大小
65             'backupCount': 5,#最多保存五份日志,写完五份时轮转
66             'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
67         },
68     },
69 
70     'loggers': {
71         #logging.getLogger(__name__)拿到的logger配置
72         '': {#定义日志的名字
73             'handlers': ['access', 'stream','boss'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
74             'level': 'DEBUG',
75             'propagate': False,  # 向上(更高level的logger)传递
76         },
77     },
78 }
79 
80 
81 
82 
83 logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置
84 l1=logging.getLogger('egon')
85 l1.error('测试')
logging

 

2、while循环购物车

  1 #购物车
  2 goods    =    [
  3 {"name":"电脑","price":1999},
  4 {"name":"鼠标","price":10},
  5 {"name":"游艇","price":20},
  6 {"name":"美女","price":98},
  7 ]
  8 def print_log(msg,log_type='info'):
  9     if log_type=='info':
 10         print('\033[32;1m%s\033[0m'%msg)
 11     elif log_type=='error':
 12         print('\033[31;1m%s\033[0m'%msg)
 13 shopping_cart=[]
 14 money=int(input('余额充值:'))
 15 while True:
 16     print('余额:',money)
 17     a='%s--%s---%s'%('商品号','name','price')
 18     print('------商品列表-------'+'\n',a)
 19     for index,i in enumerate(goods):
 20         print('  %s-------%s----%s'%(index,i['name'],i['price']))
 21     choice=input('请输入购买商品号:')
 22     if choice.isdigit():
 23         choice=int(choice)
 24         if choice>=0 and choice<len(goods):
 25             if money>=goods[choice]['price']:
 26                 money=money-goods[choice]['price']
 27                 shopping_cart.append(goods[choice])
 28                 print('商品%s成功加入购物车'%goods[choice],'info')
 29             else:
 30                 print_log('余额不足请充值!','error')
 31         else:
 32             print_log('没有此商品请重新输入!','error')
 33     if choice=='q':
 34         print('已购买的商品:','info')
 35         a = '%s--%s---%s' % ('商品号', 'name', 'price')
 36         print( '------商品列表-------' + '\n', a, )
 37         for index, i in enumerate ( shopping_cart ) :
 38             print( '  %s-------%s----%s' % (index, i ['name'], i ['price']) ,'info')
 39         print( '余额:', money )
 40         break
 41     else:
 42         print_log('退出请输入q','info')
 43 
 44 
 45 
 46 #模拟数据库信息的读取与写入
 47 goods_cart = [
 48     {'name': '鼠标', 'price': 10, 'count': 5},
 49     {'name': '游艇', 'price': 20, 'count': 15},
 50     {'name': '美女', 'price': 100, 'count': 25}
 51 ]
 52 goods_cart_list = {}
 53 goods_cart_dict={
 54     'alex':{
 55         'password':'alex123',
 56         'lock_status':'1',
 57         'balance':'4598',
 58         'shopping_cart':goods_cart_list,
 59         }
 60 }
 61 
 62 
 63 for line in goods_cart:
 64     goods_cart_list[line['name']]={
 65         'count':line['count'],
 66         'price':line['price']
 67     }
 68 
 69 for username in goods_cart_dict:
 70     user_info_list = [username]
 71     user_temp_list = []
 72     for item in goods_cart_dict[username]:
 73         if item == 'shopping_cart' and goods_cart_dict[username].get('shopping_cart'):
 74             for name in goods_cart_dict[username][item]:
 75                 user_temp_list.append(name)
 76                 for i in [list(i) for i in goods_cart_dict[username][item][name].items()]:
 77                     print(1,i)
 78                     user_temp_list.extend(i)
 79             user_info_list.extend(user_temp_list)
 80         else:
 81             goods = goods_cart_dict[username][item]
 82             if goods:
 83                 user_info_list.append(goods)
 84     print(user_info_list)
 85 #
 86 
 87 # a=['鼠标','count','5','price','10','游艇','count','5','price','10']
 88 
 89 # def chunks(msg,n):
 90 #     b=[msg[i:i+n] for i in range(0,len(msg),5)]
 91 #     return b
 92 #
 93 # list_cat=chunks(a,5)
 94 # print(list_cat)
 95 # dic={}
 96 # for i in range(0,len(a),5):
 97 #     dic[a[i]]={}
 98 #     for j in range(i+1,i+5,2):
 99 #         dic[a[i]][a[j]]=a[j+1]
100 # print(dic)
101 
102 
103 
104 # shopping_cart = {
105 #     '鼠标':{
106 #         'count':5,
107 #         'price':10
108 #     },
109 #     '游艇':{
110 #         'count':5,
111 #         'price':20
112 #     }
113 # }
购物车

 

3、三级菜单作业

 1 menu = {
 2     '北京' : {
 3         '海淀' : {
 4             '五道口' : {
 5                 'soho' : { },
 6                 '网易' : { },
 7                 'google' : { },
 8                 },
 9             '中关村' : {
10                 '爱奇艺' : { },
11                 '汽车之家' : { },
12                 'youku' : { },
13                 },
14             '上地' : {
15                 '百度' : { },
16                 },
17             },
18         '昌平' : {
19             '沙河' : {
20                 '老男孩' : { },
21                 '北航' : { },
22                 },
23             '天通苑' : { },
24             '回龙观' : { },
25             },
26         '朝阳' : { },
27         '东城' : { },
28         },
29     '上海' : {
30         '闵行' : {
31             '人民广场' : {
32                 '炸鸡店' : { },
33                 },
34             },
35         '闸北' : {
36             '火车站' : {
37                 '携程' : { },
38                 },
39             },
40         '浦东' : { },
41         },
42     '山东' : { },
43     }
44 
45 # 方法二
46 # 逻辑分析:
47 # layers=[menu,]
48 # while True:
49 #     if len(layers) == 0:break
50 # #1 拿到当前层的菜单字典
51 #     current_layer = layers[-1]
52 # #2 循环打印字典的key
53 #     for key in current_layer.keys():
54 #         print(key)
55 #
56 # #3 接收用户输入
57 #     choice = input('>>:  ').strip()
58 #     if choice == 'q':break
59 #     if choice == 'b':
60 #         layers.pop()
61 #         continue
62 #     if choice not in current_layer:continue
63 # #4 进入下一层
64 #     layers.append(current_layer[choice])
65 
66 #1,拿到当前层字典
67 #2,循环打印字典的key
68 #3,接收用户输入
69 #4,进入下一层
70 layers=[menu,]
71 while True:
72     if len(layers)==0:break
73     current_layer=layers[-1]
74     for key in current_layer:
75         print(key)
76     choice=input('>>:').strip()
77     if choice=='q':
78         break
79     if choice=='b':
80         layers.pop()
81         continue
82     if choice not in current_layer:continue
83     layers.append(current_layer[choice])
三级菜单

 

4、账户登录

 1 dic={
 2     'alex':{'password':'abc','count':0},
 3     'egon':{'password':'abc','count':0},
 4     'jack':{'password':'abc','count':0},
 5     }
 6 
 7 
 8 dic_info={
 9     'username':{'alex':0},
10 }
11 
12 while True:
13     name=input('username>>:')
14     if not name in dic:
15         print('\033[35;1m账户不存在\033[0m')
16         continue
17     with open('db','r') as f:
18         lock_users= [i.strip() for i in f.read().split('|')]
19         if name in lock_users:
20             print('账户%s已被锁定!!!'%name)
21             break
22         
23             
24     if dic[name]['count']>2:
25         print('\033[31;1m尝试次数过多,被锁定!\033[0m')
26         with open('db','a',encoding = 'utf=8') as f :
27             f.write('%s |'%name)
28         break
29     
30     password=input('pwd>>:')
31     if dic[name]['password']==password:
32         print('\033[32;1m welcome  %s  successful\033[0m'%name)
33         # tag=True
34         # while tag:
35         #     choose=['quit','exit','q','e']
36         #     cmd_th=input('cmd>>:')
37         #     print ( '%s  命令正在执行......' % cmd_th )
38         #     for i in choose:
39         #         if cmd_th==i:
40         #             print('正在退出控制台...')
41         #             tag=False
42         # break
43     else:
44         print('\033[31;1m账户密码错误\033[0m')
45         dic[name]['count'] +=1
账户登录

 

5、字典操作

 1 # -*- coding:UTF-8 -*-
 2 user_info_dict={}
 3 user_info_to_write=list()
 4 with open('shopping_cart','r+',encoding = 'utf-8') as f:
 5     for line in f:
 6         line=line.strip().split(',')
 7         shopping_history=True if len(line) > 4 else False
 8         goods_list = line[4::]
 9         shopping_cart=dict(zip(goods_list[0::2],goods_list[1::2]) if shopping_history else dict())
10 
11         user_info_dict[line[0]]={
12             'password':line[1],
13             'lock_status':line[2],
14             'balance':line[3],
15             'shopping_cart_info':shopping_cart
16             }
17     print(user_info_dict)
18 
19     for username in user_info_dict.keys():
20         user_info_list=[username]
21         user_temp_list=[]
22         for item in user_info_dict[username].keys():
23             if item == 'shopping_cart_info' and user_info_dict[username].get('shopping_cart_info'):
24                 for item in [list(item) for item in user_info_dict[username][item].items()]:
25                     user_temp_list.extend(item)
26                 user_info_list.extend(user_temp_list)
27             else:
28                 goods = user_info_dict[username][item]
29                 if goods:
30                     user_info_list.append(goods)
31         user_info_to_write.append(user_info_list)
32 goods_to_write='\n'.join(','.join(item) for item in user_info_to_write)
33 with open('db','a',encoding = 'utf-8') as f1:
34     f1.write(goods_to_write+'\n')
35 
36 
37 
38 user_info_l={
39     'alex':{
40         'password':'alex123',
41         'lock_status':'1',
42         'balance':'4598',
43         'shopping_cart':{
44             '游艇':'1',
45             '苹果':'20',
46             },
47         },
48     'egon':{
49         'password':'egon123',
50         'lock_status':'1',
51         'balance':'1000',
52         'shopping_cart':{
53             '电脑':'5',
54             '手机':'10',
55             },
56         },
57     
58     }
字典操作

 

6、购物车作业

  1 # # -*- coding:utf-8 -*-
  2 # user_info = 'shopping_cart'
  3 # user_info_dict={}#读取数据库信息,并存成字典
  4 # uname_info = [] #存入用户登录信息,用于购物
  5 # while True:
  6 #     with open(user_info,'r',encoding='utf-8') as f:#先读取数据库信息
  7 #         for line in f:
  8 #             shopping_cart = {}
  9 #             line = line.strip().split(',')
 10 #             if len(line) > 3:
 11 #                 goods_list_temp = line[3::]
 12 #                 for i in range(0,len(goods_list_temp),5):
 13 #                     shopping_cart[goods_list_temp[i]]={}
 14 #                     for j in range(i+1,i+5,2):
 15 #                         shopping_cart[goods_list_temp[i]][goods_list_temp[j]] = goods_list_temp[j+1]
 16 #             user_info_dict[line[0]] = {
 17 #                 'password':line[1],
 18 #                 'lock_status':0,
 19 #                 'balance':line[2],
 20 #                 'shopping_car':shopping_cart,
 21 #             }
 22 #
 23 #     msg = '''
 24 #     1 登录
 25 #     2 注册
 26 #     3 购物
 27 #     '''
 28 #     print(msg)
 29 #     choice = input('\033[32;1m输入服务编号>>:\033[0m').strip()
 30 #
 31 #     #第一步注册
 32 #     if choice == '2':
 33 #         print('------正在注册------')
 34 #         user_list_record = []  #临时存放注册用户信息
 35 #         while True:
 36 #             choice_name = input('\033[33;1m请输入用户名>>:\033[0m').strip()
 37 #             if choice_name in user_info_dict:#判断用户是否已存在
 38 #                 print('\033[31;1m用户已存在,请重新输入...>>:\033[0m')
 39 #                 continue
 40 #             choice_pwd_f = input('\033[33;1m请输入密码>>:\033[0m').strip()
 41 #             choice_passwd_s = input('\033[33;1m请再次输入密码>>:\033[0m').strip()
 42 #             if choice_pwd_f != choice_passwd_s: #判断密码是否一致
 43 #                 print('\033[31;1m密码不一致!请重新输入....\033[0m')
 44 #                 continue
 45 #             else:
 46 #                 choice_labary = input('\033[33;1m注册成功!\n请输入额度>>:\033[0m')
 47 #                 user_list_record=[choice_name,choice_pwd_f,choice_labary]
 48 #                 break
 49 #         user_list_record_write = ','.join(user_list_record)#把注册信息写入到文本
 50 #         with open(user_info,'a',encoding='utf-8') as f:
 51 #             f.write(user_list_record_write+'\n')
 52 #
 53 #     #第二步登录
 54 #     elif choice == '1':
 55 #         if len(user_info_dict) == 0:
 56 #             print('无用户信息,请注册!')
 57 #             continue
 58 #         print('------欢迎登录------')
 59 #         while True:
 60 #             name_inp = input('\033[35;1m用户名>>:\033[0m')
 61 #             if name_inp not in user_info_dict:
 62 #                 print('\033[31;1m用户不存在!\033[0m')
 63 #                 continue
 64 #
 65 #             with open('db','r',encoding='utf-8') as f:#读取锁定账户信息
 66 #                 line = f.read().strip()
 67 #                 if name_inp in line:
 68 #                     print('%s账户已被锁定'%name_inp)
 69 #                     break
 70 #
 71 #             if user_info_dict[name_inp]['lock_status'] > 2:
 72 #                 print('\033[31;1m尝试次数过多,账户已被锁定!:\033[0m')
 73 #                 with open('db','a',encoding='utf-8') as f:
 74 #                     f.write('%s |'%name_inp)
 75 #                 break
 76 #
 77 #
 78 #             pwd_inp = input('\033[35;1m密码>>:\033[0m')
 79 #             if pwd_inp == user_info_dict[name_inp]['password']:
 80 #                 uname_info=[name_inp,user_info_dict[name_inp]['balance']]
 81 #                 print('\033[36;1m登录成功!用户名:%s ;余额: %s \033[0m'%(uname_info[0],uname_info[1]))
 82 #                 break
 83 #             else:
 84 #                 print('\033[31;1m密码错误!重新输入!:\033[0m')
 85 #                 user_info_dict[name_inp]['lock_status'] += 1
 86 #
 87 #     #第三步购物
 88 #     elif choice == '3':
 89 #         if len(uname_info) == 0:
 90 #             print('请先登录')
 91 #             continue
 92 #         print('欢迎进入购物商城,祝您购物愉快!')
 93 #         print('\033[36;1m用户信息>>>   用户名:%s ;余额: %s \033[0m'%(uname_info[0],user_info_dict[uname_info[0]]['balance']))
 94 #         goods_cart = []  #存放购物信息
 95 #         while True:
 96 #             price_sum = 0 #定义购买商品总价格
 97 #             balance_m = int(user_info_dict[uname_info[0]]['balance'])#把字典内商品价格转换为整型,进行价格运算
 98 #             goods = [
 99 #                 {"name":"电脑","price":'2000'},
100 #                 {"name":"鼠标","price":'10'},
101 #                 {"name":"游艇","price":'20'},
102 #                 {"name":"美女","price":'100'},
103 #             ]
104 #             print('-------商品列表-------'+'\n','编号   名称   价格')
105 #             for index,line in enumerate(goods):
106 #                 print(' %s     %s     %s'%(index,line['name'],line['price']))
107 #             choice_g = input('请输入购买物品编号>>:').strip()
108 #             if choice_g.isdigit():
109 #                 choice_g = int(choice_g)
110 #                 if choice_g >=0 or choice_g < len(goods):
111 #                     buy_num = int(input('请输入购买件数>>:').strip()) #购买商品的个数
112 #                     goods[choice_g]['count'] = 0
113 #                     goods[choice_g]['count'] += buy_num
114 #                     goods[choice_g]['count'] =str(goods[choice_g]['count'])
115 #
116 #                     goods_cart.append(goods[choice_g]) #购买的商品添加到购物车
117 #                     print('商品%s成功加入购物车,退出结算请输入q'%goods[choice_g])
118 #                 else:
119 #                     print('没有此商品!')
120 #             if choice_g == 'q':
121 #                 goods_list = '''
122 #                 ---------------------已购买商品列表-------------------
123 #                     商品编号       商品名称      商品价格     商品个数
124 #                 '''
125 #                 print(goods_list)
126 #                 for index,line in enumerate(goods_cart):
127 #                     print('                         %s              %s          %s         %s'%(index,line['name'],line['price'],line['count']))
128 #                     price_sum += int(line['price'])*int(line['count'])
129 #                 print('账户余额:%s'%user_info_dict[uname_info[0]]['balance'],''.center(60),'价格总计: %s'%price_sum)
130 #                 choice_goods_math = input('               商品结算或退出请输入yes/no:').strip()
131 #                 if choice_goods_math == 'no':break
132 #                 if choice_goods_math == 'yes':
133 #                     if balance_m >= price_sum:
134 #                         user_info_to_write = []
135 #                         price_inp = balance_m - price_sum
136 #                         price_inp = str(price_inp)
137 #                         user_info_dict[uname_info[0]]['balance']=price_inp #把结算后的价格存入字典内
138 #                         for line in goods_cart:#把购物信息存入购物字典内
139 #                             user_info_dict[uname_info[0]]['shopping_car'][line['name']] = {
140 #                                 'count':line['count'],
141 #                                 'price':line['price']
142 #                             }
143 #                         for username in user_info_dict.keys():#读取内存中的用户信息,并写入到数据库中
144 #                             user_info_list = [username]
145 #                             user_temp_list = []
146 #                             for item in user_info_dict[username].keys():
147 #                                 if item == 'shopping_car' and user_info_dict[username].get('shopping_car'):
148 #                                     for name in user_info_dict[username][item].keys():
149 #                                         user_temp_list.append(name)
150 #                                         for i in [list(i)for i in user_info_dict[username][item][name].items()]:
151 #                                             user_temp_list.extend(i)
152 #                                     user_info_list.extend(user_temp_list)
153 #                                 else:
154 #                                     good_s = user_info_dict[username][item]
155 #                                     if good_s:
156 #                                         user_info_list.append(good_s)
157 #                             user_info_to_write = user_info_list
158 #                         goods_to_write = ','.join(user_info_to_write)
159 #                         with open(user_info,'w',encoding='utf-8') as f:#把购物信息写入数据库中(文本文件)
160 #                             f.write(goods_to_write+'\n')
161 #                         print('购物总消费: %s   余额: %s'%(price_sum,price_inp))
162 #                         break
163 #                     else:
164 #                         print('余额不足请充值! 余额:%s'%user_info_dict[uname_info[0]]['balance'])
165 #                         inp_money = int(input('请输入充值金额:').strip())
166 #                         money = inp_money + int(user_info_dict[uname_info[0]]['balance'])
167 #                         user_info_dict[uname_info[0]]['balance'] =str(money)
168 #     elif choice == 'q':
169 #         print('已退出购物商城')
170 #         break
171 #     else:
172 #         print('输入字符非法!')
173 
174 import os
175 
176 product_list = [['Iphone7',5800],
177                 ['Coffee',30],
178                 ['疙瘩汤',10],
179                 ['Python Book',99],
180                 ['Bike',199],
181                 ['ViVo X9',2499],
182 
183                 ]
184 
185 shopping_cart={}
186 current_userinfo=[]#用户名和余额
187 
188 db_file=r'db.json'
189 
190 while True:
191     print('''
192     1 登陆
193     2 注册
194     3 购物
195     ''')
196 
197     choice=input('>>: ').strip()
198 
199     if choice == '1':
200         #1、登陆
201         tag=True
202         count=0
203         while tag:
204             if count == 3:
205                 print('\033[45m尝试次数过多,退出。。。\033[0m')
206                 break
207             uname = input('用户名:').strip()
208             pwd = input('密码:').strip()
209 
210             with open(db_file,'r',encoding='utf-8') as f:
211                 for line in f:
212                     line=line.strip('\n')
213                     user_info=line.split(',')
214 
215                     uname_of_db=user_info[0]
216                     pwd_of_db=user_info[1]
217                     balance_of_db=int(user_info[2])
218 
219                     if uname == uname_of_db and pwd == pwd_of_db:
220                         print('\033[48m登陆成功\033[0m')
221 
222                         # 登陆成功则将用户名和余额添加到列表
223                         current_userinfo=[uname_of_db,balance_of_db]
224                         print('用户信息为:',current_userinfo)
225                         tag=False
226                         break
227                 else:
228                     print('\033[47m用户名或密码错误\033[0m')
229                     count+=1
230 
231     elif choice == '2':
232         uname=input('请输入用户名:').strip()
233         while True:
234             pwd1=input('请输入密码:').strip()
235             pwd2=input('再次确认密码:').strip()
236             if pwd2 == pwd1:
237                 break
238             else:
239                 print('\033[39m两次输入密码不一致,请重新输入!!!\033[0m')
240 
241         balance=input('请输入充值金额:').strip()
242 
243         with open(db_file,'a',encoding='utf-8') as f:
244             f.write('%s,%s,%s\n' %(uname,pwd1,balance))
245 
246     elif choice == '3':
247         if len(current_userinfo) == 0:
248             print('\033[49m请先登陆...\033[0m')
249         else:
250             #登陆成功后,开始购物
251             uname_of_db=current_userinfo[0]
252             balance_of_db=current_userinfo[1]
253 
254             print('尊敬的用户[%s] 您的余额为[%s],祝您购物愉快' %(
255                 uname_of_db,
256                 balance_of_db
257             ))
258 
259             tag=True
260             while tag:
261                 for index,product in enumerate(product_list):
262                     print(index,product)#打印购物商品列表
263                 choice=input('输入商品编号购物,输入q退出>>: ').strip()
264                 if choice.isdigit():
265                     choice=int(choice)
266                     if choice < 0 or choice >= len(product_list):continue
267 
268                     pname=product_list[choice][0]#商品名
269                     pprice=product_list[choice][1]#价格
270 
271                     if balance_of_db > pprice:
272                         if pname in shopping_cart: # 原来已经购买过
273                             shopping_cart[pname]['count']+=1
274                         else:
275                             shopping_cart[pname]={'pprice':pprice,'count':1}
276 
277                         balance_of_db-=pprice # 扣钱
278                         current_userinfo[1]=balance_of_db # 更新用户余额
279                         print("Added product " + pname + " into shopping cart,\033[42;1myour current\033[0m balance " + str(balance_of_db))
280 
281                     else:
282                         print("买不起,穷逼! 产品价格是{price},你还差{lack_price}".format(
283                             price=pprice,
284                             lack_price=(pprice - balance_of_db)
285                         ))
286                     print(shopping_cart)
287                 elif choice == 'q':
288                     print("""
289                     ---------------------------------已购买商品列表---------------------------------
290                     id          商品                   数量             单价               总价
291                     """)
292 
293                     total_cost=0
294                     for i,key in enumerate(shopping_cart):
295                         print('%22s%18s%18s%18s%18s' %(
296                             i,
297                             key,
298                             shopping_cart[key]['count'],
299                             shopping_cart[key]['pprice'],
300                             shopping_cart[key]['pprice'] * shopping_cart[key]['count']
301                         ))
302                         total_cost+=shopping_cart[key]['pprice'] * shopping_cart[key]['count']
303 
304                     print("""
305                     您的总花费为: %s
306                     您的余额为: %s
307                     ---------------------------------end---------------------------------
308                     """ %(total_cost,balance_of_db))
309 
310                     while tag:
311                         inp=input('确认购买(yes/no?)>>: ').strip()
312                         if inp not in ['Y','N','y','n','yes','no']:continue
313                         if inp in ['Y','y','yes']:
314                             # 将余额写入文件
315 
316                             src_file=db_file
317                             dst_file=r'%s.swap' %db_file
318                             with open(src_file,'r',encoding='utf-8') as read_f,\
319                                 open(dst_file,'w',encoding='utf-8') as write_f:
320                                 for line in read_f:
321                                     if line.startswith(uname_of_db):
322                                         l=line.strip('\n').split(',')
323                                         l[-1]=str(balance_of_db)
324                                         line=','.join(l)+'\n'
325 
326                                     write_f.write(line)
327                             os.remove(src_file)
328                             os.rename(dst_file,src_file)
329 
330                             print('购买成功,请耐心等待发货')
331 
332                         shopping_cart={}
333                         current_userinfo=[]
334                         tag=False
335 
336 
337                 else:
338                     print('输入非法')
339 
340 
341     else:
342         print('\033[33m非法操作\033[0m')
购物车作业

 

7、logging模块原理

 1 import logging
 2 
 3 #basicConfig功能
 4 logging.basicConfig(
 5     filename='access.log',#指定文件的路径,默认在屏幕上打印
 6     # filemode=''#打印方式w模式或a模式,默认为a追加模式,因此不需要指定
 7 
 8     format='%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s',#定制日志格式
 9     #        日志时间           日志名称        日志级别           模块名      日志具体信息
10 
11     datefmt='%Y-%m-%d  %H:%M:%S  %p',#定制时间格式
12     level=30,#设置日志的级别
13 )
14 
15 #打印示例
16 '''
17 2018-08-08  15:09:34  PM - root - DEBUG - 02 logging模块: debug.......
18 2018-08-08  15:09:34  PM - root - INFO - 02 logging模块: info.......
19 2018-08-08  15:09:34  PM - root - WARNING - 02 logging模块: 可能要着火
20 2018-08-08  15:09:34  PM - root - ERROR - 02 logging模块: 着火了,快跑
21 2018-08-08  15:09:34  PM - root - CRITICAL - 02 logging模块: 火越烧越大
22 '''
23 
24 
25 
26 
27 
28 
29 logging.debug('debug.......')#调试信息  10
30 logging.info('info.......')#程序正常运行的一些信息  20
31 logging.warning('可能要着火')#程序警告信息(不是致命信息,有可能会出问题) 30
32 logging.error('着火了,快跑')#程序出现严重错误  40
33 logging.critical('火越烧越大')#程序已经崩溃  50
34 
35 #日志特点:如果日志级别设置为10,那么20,30,40,50日志级别都可以打印,
36          # 如果日志级别设置为30,只能打印30,40,50级别的日志,
37          #可以控制打印日志级别,日志打印只能打印设置级别更高的级别的日志,
38 
39 
40 
41 
42 
43 #log: 负责产生日志
44 logger1=logging.getLogger('xxx')
45 
46 #ilter: 过滤日志(不常用)
47 
48 
49 #handler: 控制日志打印到文件or终端
50 fh1=logging.FileHandler(filename='a1.log',encoding='utf-8')
51 #往文件打印
52 fh2=logging.FileHandler(filename='a2.log',encoding='utf-8')
53 #往终端打印
54 sh=logging.StreamHandler()
55 
56 
57 #formatter: 控制日志的格式
58 formatter1=logging.Formatter(
59     fmt='%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s',
60     datefmt='%Y-%m-%d %H:%M:%S %p'
61 )
62 formatter2=logging.Formatter(fmt='%(asctime)s - %(message)s',)
63 
64 
65 
66 
67 #为logger对象绑定handler
68 logger1.addHandler(fh1)
69 logger1.addHandler(fh2)
70 logger1.addHandler(sh)
71 
72 #为handler对象绑定日志格式
73 fh1.setFormatter(formatter1)
74 fh2.setFormatter(formatter1)
75 
76 sh.setFormatter(formatter2)
77 
78 
79 
80 #日志级别:两层关卡必须都通过,日志才能正常记录
81 logger1.setLevel(10)
82 fh1.setLevel(10)
83 fh2.setLevel(10)
84 sh.setLevel(10)
85 
86 logger1.debug('调试信息')
logging原理

 

8、转账功能

 1 # db_path='db.json'
 2 #
 3 # #1、源账户减钱
 4 # def cal_mon(src_user,money):
 5 #     pass
 6 #
 7 # #2、目标账户加钱
 8 # def add_mon(dst_user,money):
 9 #     pass
10 #
11 #
12 # def transfer(src_user,dst_user,money):
13 #     cal_mon(src_user,money)
14 #     add_mon(dst_user,money)
15 #
16 #
17 # transfer('egon','alex',300)
18 
19 #原账户减钱
20 def cal_mon(src_mon,monery):
21     pass
22 #新账户加钱
23 def add_mon(dst_mon,monery):
24     pass
25 
26 def transfer(src_mon,dst_mon,monery):
27     cal_mon(src_mon,monery)
28     add_mon(dst_mon,monery)
29 
30 transfer('alex','egon',300)
函数格式

 

9、函数递归调用

 1 # -*- coding:utf-8 -*-
 2 #三元运算
 3 def max2(x,y):
 4     return x if x>y else y
 5 
 6 
 7 res=max2(max2(10,11),12)
 8 print(res)
 9 
10 res=10 if 10 > 11 else 11
11 print(res)
12 
13 #内置函数
14 #lambda匿名函数的应用
15 #max,min,sorted
16 salaries={
17     'egon':3000,
18     'alex':100000000,
19     'wupeiqi':10000,
20     'yuanhao':2000,
21 }
22 
23 #求工资最高的人是谁
24 def get(k):
25     return salaries[k]
26 
27 print(max(salaries,key=lambda x:salaries[x]))
28 
29 #求工资最低的人是谁
30 print(min(salaries,key=lambda x:salaries[x]))
31 
32 #把字典按照薪资高低排序
33 print(sorted(salaries,key=lambda x:salaries[x],reverse=True))#降序
34 
35 
36 
37 
38 #lambda与map,reduce,filter
39 nums=[1,2,3,4,5]
40 
41 res=map(lambda x:x**2,nums)
42 print(list(res))
43 
44 names=['alex','wupeiqi','yuanhao']
45 res=map(lambda x:x+'_SB',names)
46 print(list(res))
47 
48 names=['alex','wupeiqi','yuanhao','egon']
49 res=map(lambda x:x+'_NB' if x=='egon' else x+'_SB',names)
50 print(list(res))
51 
52 
53 # reduce
54 #1加到100等于几
55 from functools import reduce
56 
57 res=reduce(lambda x,y:x+y,range(1,101))
58 print(res)
59 
60 l=['my','name','is','alex','alex','is','sb']
61 res=reduce(lambda x,y:x+' '+y+' ',l)
62 print(res)
63 
64 
65 #filter
66 names=['alex_sb','wxx_sb','yxx_sb','egon']
67 res=filter(lambda x:x.endswith('sb'),names)
68 
69 ages=[18,19,10,23,99,30]
70 res=filter(lambda n:n>=30,ages)
71 print(list(res))
72 
73 salaries={
74     'egon':3000,
75     'alex':100000000,
76     'wupeiqi':10000,
77     'yuanhao':2000,
78 }
79 res=filter(lambda k:salaries[k]>=10000,salaries)
80 print(list(res))
函数递归调用

 

10、函数装饰器

叠加多个饰器
 1 # -*- coding:utf-8 -*-
 2 import time
 3 current_user={
 4     'username':None,
 5 }
 6 db_path='db'
 7 
 8 def auth(engine):
 9     # engine='file'
10     def auth2(func):
11         def wrapper(*args,**kwargs):
12             if engine =='file':
13                 while True:
14                     if current_user['username']:
15                         print('用户已登录')
16                         res = func(*args,**kwargs)
17                         return res
18 
19                     uname=input('用户名>>:').strip()
20                     pwd=input('密码>>:').strip()
21                     with open(r'%s'%db_path,'r',encoding='utf-8')as f:
22                         for line in f:
23                             line=line.strip('\n').split(',')
24                             if uname==line[0] and pwd==line[1]:
25                                 current_user['username']=uname
26                                 res=func(*args,**kwargs)
27                                 return res
28                         else:
29                             print('用户名或密码错误')
30             elif engine=='mysql':
31                 print('基于MySql的认证')
32             elif engine=='ldap':
33                 print('基于Ldap的认证')
34 
35         return wrapper
36     return auth2
37 auth_src=auth('ldap')
38 
39 @auth('mysql')
40 def index():
41     time.sleep(2)
42     print('welcome to index page')
43     return 122
44 index()
有参装饰器

 

转载于:https://www.cnblogs.com/happyfei/p/9639886.html

你可能感兴趣的:(基础知识练习)