python 入门第三课 函数function

1、函数定义: 函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可
特性:
减少重复代码
使程序变的可扩展
使程序变得易维护

函数调用时,位置参数必须提供,默认参数可以不输入,介于位置参数后面,对于不确定个数的位置参数,函数定义时可以使用args,将多个不确定的位置参数转换为元组形式的参数,函数调用时也可以使用[]方式,对于多个不确定个数的关键字参数,函数定义时可以使用**kwargs,将多个不确定的关键字参数转换为字典形式的参数,函数调用时也可以使用{key:value}方式,

__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}

2、递归:函数内部调用自己

递归特性:

  1. 必须有一个明确的结束条件
  2. 每次进入更深一层递归时,问题规模相比上次递归都应有所减少
  3. 递归效率不高,递归层次过多会导致栈溢出
__author__ = 'admin'

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

calc(10)

3、配置文件的信息计数1、查找信息2、增加写入3、删除信息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 www

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

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

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

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、函数即变量:
4.1.1 高阶函数:
4.1.1a、 将函数名作为形参传给另一个函数(在不修改被装饰函数源代码的情况下为其添加功能)

扫描二维码关注公众号,回复: 3929488 查看本文章
__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()

运行结果示例:

5、 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()

6、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

猜你喜欢

转载自www.cnblogs.com/chongmao/p/9885219.html