python 入門第三課 函數function

一、函數定義: 函數是指將一組語句的集合經過一個名字(函數名)封裝起來,要想執行這個函數,只需調用其函數名便可
特性:
減小重複代碼
使程序變的可擴展
使程序變得易維護web

函數調用時,位置參數必須提供,默認參數能夠不輸入,介於位置參數後面,對於不肯定個數的位置參數,函數定義時可使用args,將多個不肯定的位置參數轉換爲元組形式的參數,函數調用時也可使用[]方式,對於多個不肯定個數的關鍵字參數,函數定義時可使用**kwargs,將多個不肯定的關鍵字參數轉換爲字典形式的參數,函數調用時也可使用{key:value}方式,app

__author__ = 'admin'
def test(x,y=2,*args,**kwargs):
    print(x)
    print(y)
    print(args)
    print(kwargs)

test(2)
test(2,5,8,9,12)
test(2,5,*[8,9,12])
test(2,5,*[8,9,12],name = 'chongmao',age = 23)
test(2,5,*[8,9,12],**{'name':  'alex','age':  20})

最後一行輸出:
2
5
(8, 9, 12)
{'name': 'alex', 'age': 20}frontend

二、遞歸:函數內部調用本身函數

遞歸特性:3d

  1. 必須有一個明確的結束條件
  2. 每次進入更深一層遞歸時,問題規模相比上次遞歸都應有所減小
  3. 遞歸效率不高,遞歸層次過多會致使棧溢出
__author__ = 'admin'

def calc(n):
    print(n)
    if int (n/2)>0 :
        return calc(int(n/2))
    print('---->:',n)

calc(10)

三、配置文件的信息計數一、查找信息二、增長寫入三、刪除信息4
配置文件寫於‘TEXTpy2’中,待寫入或刪除的內容 讀取於字典arg中。choice ==1,讀取 行以backend開始的行數,計數;choice ==2,提示輸入一個網址如‘www.oldboy5.org’,以列表的方式讀取文件內容,判斷輸入的內容是否在列表的元素中,若是在,則輸出下一行即列表下一個元素的的詳細信息;choice ==3,分兩行寫入字典arg中的內容,以格式化的方式寫入TEXTpy2的文末;choice ==4,readlines()以列表方式讀取全部內容,過濾掉待刪除的內容,從新寫入新文件。
初始TEXTpy2文件以下:
frontend oldboy.org
bind 0.0.0.0:80
option httplog
option httpclose
option forwardfor
log global
acl www hdr_reg(host) -i www.oldboy.org
use_backend www.oldboy.org if wwwcode

backend www.oldboy.org
server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000orm

backend www.oldboy5.org
server 100.1.7.9 100.1.7.11 weight 20 maxconn 300server

backend www.oldboy7.org
server 100.1.7.9 100.1.7.7 weight 20 maxconn 3000blog

backend www.oldboy8.org
server 100.1.7.8 weight 20 maxconn 30遞歸

__author__ = 'admin'

arg = {
            'backend': 'www.oldboy6.org',
            'record':{
                'server': '100.1.7.8',
                'weight': 20,
                'maxconn': 30
            }
        }
choice = input('input a number : 1 for count,2 for search,3 for new write,4 for delete:')

if choice =='1':
    with open('TEXTpy2','r',encoding='utf-8') as fcount :
        count = 0
        for line in fcount:
            # fline = fcount.readline()
            if fcount.readline().startswith('backend '):
                print(fcount.readline().strip())
                count+=1
        print(count)

elif choice =='2':
    f_input = input('please input a website:')
    f_in_line = 'backend '+f_input+'\n'
    print(f_in_line)
    with open('TEXTpy2','r',encoding='utf-8') as fsearch :
        lines = fsearch.readlines()
        for i in range(len(lines)):
            if f_in_line in lines[i] :
                print('The detail information is:',lines[i+1].strip())

elif choice =='3':
    f_w = '\nbackend '+arg['backend']
    f_w_info = '        server '+arg['record']['server']+' weight %s maxconn %s'%(arg['record']['weight'],arg['record']['maxconn'])
    with open('TEXTpy2','r+',encoding='utf-8') as f_write :
        if f_w.strip()+'\n' in f_write :
            print('The web exists')
        else:
            f_write.write('\n')
            f_write.write(f_w)
            f_write.write('\n')
            f_write.write(f_w_info)
            f_write.seek(0)
            print(f_write.readlines())

elif choice =='4':
    f_w = 'backend '+arg['backend']+'\n'
    f_w_info = '        server '+arg['record']['server']+' weight %s maxconn %s'%(arg['record']['weight'],arg['record']['maxconn'])
    with open('TEXTpy2','r',encoding='utf-8') as f_r :
        lines = f_r.readlines()
        print(lines)
    with open('TEXTpy2','w',encoding='utf-8') as f_rewrite :
        index_del = lines.index(f_w)
        print(index_del)
        del lines[index_del:index_del+3]
        for i in range(len(lines)):
            f_rewrite.write(lines[i])

else:
   print('Invalid input.')

四、函數即變量:
4.1.1 高階函數:
4.1.1a、 將函數名做爲形參傳給另外一個函數(在不修改被裝飾函數源代碼的狀況下爲其添加功能)

__author__ = 'Administrator'
import time
def bar():
    time.sleep(3)
    print('in the bar')

def test(func):
    start_time = time.time()
    func()
    end_time = time.time()
    print('the func run time is%s'%(end_time-start_time))

test(bar)

4.1.1b、返回值中包含函數名(不修改函數的調用方式)
嵌套函數:

def foo():
    print('in the foo')
    def bar():
        print('in the bar')
    bar()
foo()

4.1.2高階函數+嵌套函數=》裝飾器

__author__ = 'Administrator'
import time

def timer(func):
    def deco(*args,**kwargs):
        start_time = time.time()
        func(*args,**kwargs)
        end_time = time.time()
        print('the func run time is %s'%(end_time-start_time))
    return deco
@timer
def bar():
    time.sleep(3)
    print('in the bar')
@timer
def test2(name,age):
    time.sleep(1)
    print('info is:',name,age)
bar()
test2('alex',20)

4.2 裝飾器的複合應用
對不一樣的函數增長差別化的裝飾變量,須要在裝飾函數的外圍增長一層函數,並增長一層返回。

__author__ = 'Administrator'
user,password = 'alex','abc123'
def auth(auth_type):
    def out_wrapper(func):
        def wrapper(*args,**kwargs):
            if auth_type == 'local':
                username = input('username:').strip()
                password1 = input('password:').strip()
                if user ==username and password == password1 :
                    return func(*args,**kwargs)
                else:
                    exit()
            elif auth_type == 'ldap':
                print('Other way...')
        return wrapper
    return out_wrapper
def index():
    print('welcome to index page.')
@auth(auth_type = 'local')
def home():
    print('welcome to home page.')
    return 'from home'
@auth(auth_type = 'ldap')
def bbs():
    print('welcome to bbs page.')

index()
print(home())
bbs()

運行結果示例:

五、 yield生成器.__next__()和.send()使用

__author__ = 'Administrator'
import time
def consumer(name):
    print('%s prepare to eat.'%name)
    while True:
        baozi = yield
        print('baozi %s is coming ,%s will eat it'%(baozi,name))
# c = consumer('wang')
# c.__next__()
# c.__next__()
# c.__next__()
# c.send('pork')
def producer():
    c1 = consumer('A')
    c2 = consumer('B')
    c1.__next__()
    c2.__next__()
    print('Start to make baozi')
    for i in range(1,4,1):
        time.sleep(1)
        print('baozi%s is ok'%i)
        c1.send(i)
        c2.send(i)
producer()

六、try--except和yield生成斐波那契數列:

def fib(max):
    n,a,b=0,0,1
    while n <max :
#        print(b)
        yield b
        a,b = b,a+b
        n +=1
    return  '--done--'

g = fib(10)

while True:
    try :
        x = next(g)
        print('g:',x)
    except StopIteration as e:
        print('generator return value',e.value)
        break

相關文章
相關標籤/搜索