Python-基础函数与常用模块考核

第二模块考核(2019/ 03/ 03)


### 第一模块内容
1.请写出 “路飞学城alex” 分别用utf - 8和gbk编码所占的位数(口述)
➜  ~ python3
>>> bytes("", "gbk")
b'\xc4\xe3'
>>> bytes("a", "gbk")
b'a'
>>> bytes("", "utf-8")
b'\xe4\xbd\xa0'
>>> bytes("a", "utf-8")
b'a'
2.python有哪几种数据类型,分别什么?
 可变:Number,String,Tuple
 不可变:List,Dictionary,Set
### 第二模块内容
1.创建一个闭包函数需要满足哪几点。(口述)
  有内嵌函数,引用一个定义在闭合范围内的变量,外部函数必须返回内嵌函数
########## 闭包的原理解释
>>> def make_printer(msg1, msg2):
    def printer():
        print msg1, msg2
    return printer
>>> printer = make_printer('Foo', 'Bar')  # 形成闭包

>>> printer.__closure__   # 返回cell元组
(<cell at 0x03A10930: str object at 0x039DA218>, <cell at 0x03A10910: str object at 0x039DA488>)

>>> printer.__closure__[0].cell_contents  # 第一个外部变量
'Foo'
>>> printer.__closure__[1].cell_contents  # 第二个外部变量
'Bar'

2.序列化模块json,xml,pickle的区别是什么?(口述)
 参考文章:https://www.cnblogs.com/qing-add/p/5225048.html
3.迭代器和生成器的区别, 在python中它们的原理是什么。(口述) 
 参考文章:http://python.jobbole.com/87805/
      http://www.runoob.com/python3/python3-iterator-generator.html
      https://www.cnblogs.com/wj-1314/p/8490822.html
      https://www.cnblogs.com/cicaday/p/python-decorator.html
4.解释一下包和模块的含义。 (口述)
 参考文章:https://www.cnblogs.com/935415150wang/p/7091227.html


5.请阐述一下代码含义
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

 6.解释以下代码含义 (口述)
  
from functools import reduce
  reduce(lambda x, y: x + y, range(10))

 7. 字符串“Luffy”,将小写字母全部转换成大写字母,将大写字幕转换成小写字母。(编程)

word = "Luffy"
new_word = word.swapcase()
print("new_word:",new_word)
str = "www.runoob.com"
print(str.upper())          # 把所有字符中的小写字母转换成大写字母
print(str.lower())          # 把所有字符中的大写字母转换成小写字母
print(str.capitalize())     # 把第一个字母转化为大写字母,其余小写
print(str.title())          # 把每个单词的第一个字母转化为大写,其余小写

 8. 编写装饰器,为每个函数加上统计运行时间的功能。(编程)

import time
def timmer(func):
    def inner():
        star_time = time.time()
        func()
        wait_time = time.time() - star_time
        print("%s运行时间为:%s" %(func.__name__,wait_time))
    return inner
date = time.localtime()

@timmer
def log_1():
    print(date,date.tm_year,date.tm_mon)

log_1()
import time
def timmer(func):
     def wrapper(*args,**kwargs):
          start= time.time()
          func(*args,**kwargs)
          stop = time.time()
          print('执行时间是%s'%(stop-start))
      return wrapper
@timmer
def exe():
     print('你愁啥!')
exe()
import time
def timmer(func):

    def inner():
        start_time = time.time()
        func()
        wait_time = time.time() - start_time
        print("%s 运行时间:" % func.__name__, wait_time)
    return inner


a = time.localtime()

@timmer
def log_1():
    print('%s-%s-%s'%(a.tm_year, a.tm_mon, a.tm_mday))
@timmer
def log_2():
    time.sleep(2)
    print('%s-%s-%s' % (a.tm_year, a.tm_mon, a.tm_mday))
@timmer
def log_3():
    time.sleep(4)
    print('%s-%s-%s' % (a.tm_year, a.tm_mon, a.tm_mday))
log_1()
log_2()
log_3()
"""
2018-3-21
log_1 运行时间: 3.0994415283203125e-05
2018-3-21
log_2 运行时间: 2.0049030780792236
2018-3-21
log_3 运行时间: 4.004503965377808
"""

 9. 递归实现斐波那契函数。(编程)

list = []
def fib(max):
    n,a,b = 0,0,1
    while n < max:
        a,b = b,a+b
        #yield b
        n = n+1
        list.append(b)
        #print(b)
    #return 'done'
num = fib(5)
print(list)
'''
print(next(num))
print(next(num))
print(next(num))
'''

 10. random模块,写一个包含大小写字母和数字的6位随机验证码。(编程)

import random
import string

wrong_word = "".join(random.sample('a-z'+'A-Z'+'0-9',6))
right_word = "".join(random.sample(string.ascii_uppercase+string.ascii_lowercase+string.digits,6))print(right_word )
print(wrong_word )
print(wrong_word )

 其他同学的模块考核总结:https://www.cnblogs.com/wj-1314/p/8534245.html

扩展

闭包实现快速给不同项目记录日志

import logging
    def log_header(logger_name):
        logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(name)s] %(levelname)s  %(message)s',
                            datefmt='%Y-%m-%d %H:%M:%S')
        logger = logging.getLogger(logger_name)
 
        def _logging(something,level):
            if level == 'debug':
                logger.debug(something)
            elif level == 'warning':
                logger.warning(something)
            elif level == 'error':
                logger.error(something)
            else:
                raise Exception("I dont know what you want to do?" )
        return _logging
 
    project_1_logging = log_header('project_1')
 
    project_2_logging = log_header('project_2')
 
    def project_1():
 
        #do something
        project_1_logging('this is a debug info','debug')
        #do something
        project_1_logging('this is a warning info','warning')
        # do something
        project_1_logging('this is a error info','error')
 
    def project_2():
 
        # do something
        project_2_logging('this is a debug info','debug')
        # do something
        project_2_logging('this is a warning info','warning')
        # do something
        project_2_logging('this is a critical info','error')
 
    project_1()
    project_2()

--------------------- 
作者:chaseSpace-L 
来源:CSDN 
原文:https://blog.csdn.net/sc_lilei/article/details/80464645 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自www.cnblogs.com/gete54/p/10466127.html
今日推荐