1. 程式人生 > >Python-基礎函數與常用模塊考核

Python-基礎函數與常用模塊考核

日誌 pre 序列 內嵌 new number color config ict

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

技術分享圖片


### 第一模塊內容
1.請寫出 “路飛學城alex” 分別用utf - 8和gbk編碼所占的位數(口述)
?  ~ python3
>>> bytes("", "gbk")
b\xc4\xe3
>>> bytes("a", "gbk")
ba
>>> bytes("", "utf-8")
b\xe4\xbd\xa0
>>> bytes("a", "utf-8")
ba
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 
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

Python-基礎函數與常用模塊考核