The Road to Python Development - Day4 (Functions)

First, the definition of the function

def test(x)
    "The Function definitions"
    x += 1
    return x

def: keyword that defines a function

test: function name

(): define the formal parameters

"": document description

x += 1: generally refers to code block or program processing logic

return: define the return value (return occurs, the function ends)

The runtime can be called with or without parameters: function()

Advantages: code reuse, consistency, easy maintenance, scalability

2. Functions and Procedures

1. A procedure is a function without a return value. Since the return value is not used in Python, it will return None, so the procedure is also a function in Python.

2. Return value

def test01():
    pass
def test02():
    return 0
def test03():
    return 0, 10, 'hello', ['kobe', 'lbj'], {'Team': 'lakers'}
t1 = test01()
t2 = test02()
t3 = test03()
print(t1,t2,t3)
View Code

The return value is 0, returns None, the return value is 1, returns object, the return value > 1, returns tuple.

Three, function parameters

1. Formal and actual parameters

def calc(x,y): # x,y are formal parameters 
    res = x ** y
     return res
t = calc(1,2) # 1,2 are arguments 
print (t)
View Code

Formal parameters are only allocated memory units when the function is called, and are released immediately after the call, so the formal parameters are only valid inside the function

The actual parameters can be constants, variables, expressions, and functions. When the function is called, there must be a definite value in order to pass the value to the formal parameter.

2. Positional and keyword arguments

def test (x, y, z):
     print (x, y, z)
test( 1,2,3) #position parameter 
test(x=1,z=3,y=2) #keyword parameter 
test(1,y=2,z=3)
View Code

The positional parameters must be in one-to-one correspondence, not more or less, and the keyword parameters do not need to be in one-to-one correspondence, nor more or less, the two can be mixed, but the positional parameters must be on the left side of the keyword parameters, otherwise an error will be reported.

3. Default parameters

def power(x, n=2): # n is the default parameter
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    print(s)
    return(s)

power(4,4)
View Code

默认参数可以降低函数调用的难度,但设置的时候要注意,不能用可变对象

def add_end(L=[]):
    L.append('END')
    return L

# print(add_end([123,456]))
print(add_end())
print(add_end())
print(add_end())
View Code

4.参数组

def test(x,*args,**kwargs):
    print(x)
    print(args)
    print(kwargs)
test(1,2,3,4,5,y=12,z=22)
View Code

*args传的是列表或元组,**kwargs传的是字典

定义可变参数用*

def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum
s = calc(1,2,3)
print(s)
num = [1,2,3,4]
s = calc(*num)
print(s)
View Code

定义关键字参数用**

def person(name, age, **kw):
    print("name:", name, "age:", age, "other:", kw)
person("hechouzi", 25,city="jiangsu",height=183)
extra = {"city":"jiangsu","height":183}
person("heheh",12,**extra)
View Code

四、全局变量和局部变量

全局变量全部大写,局部变量全部小写

函数中如果没有global参数,且没有声明局部变量,函数内部可以调用全局变量,但不可修改

函数中如果有global参数,可以对全局变量进行修改

函数中如果定义了局部变量,则优先读取局部变量

NAME = "KOBE"
def change_name():
    global NAME
    name = "LBJ"
    print("Who am i:",NAME)
    print("Who are you:",name)
    NAME = "BYRANT"
    print("Now,who am i:",NAME)
    print("Now,who are you:",name)
change_name()
print(NAME)
print(name)#报错,因为是局部变量
View Code

五、前向引用

“函数即变量”

def test1():
    print("from test1")
    test2()
def test2():
    print("from test2")
test1()
View Code

前向引用就是在定义函数之前引用

六、嵌套函数和作用域

def test1():
    name = "Jordan"

    def test2():
        name = "Kobe"

        def test3():

            print(name)
        return test3

    return test2
func = test1
print(func)
func()()()
View Code

七、递归调用

递归特性:1.必须有一个明确的结束条件;2.进入深一层的递归,问题规模要比上一层有所减少;3.递归效率不高,递归层次过高会导致栈溢出。

(图侵删)

def calc(n):
    if int(n/2)==0:
        return n
    n = int(n/2)
    re = calc(n)
    return re
print(calc(100))
View Code

尾递归优化

如阶乘函数,当所求阶乘数太大,会导致栈溢出。

def fact(n):
    if n == 1:
        return n
    return n*fact(n-1)
print(fact(100))
View Code

尾调用就是指在一个函数的最后一步调用另外一个函数,以此来实现尾递归优化

def fact(n):
    return fact_iter(n,1);
def fact_iter(num,res):
    if num == 1:
        return res
    return fact_iter(num - 1,num*res)
print(fact(5))
View Code

尾调用优化可以不要保存外层函数的调用记录,可以防止栈溢出,但大多数编程语言没有针对尾调用优化,Python也没有。

八、匿名函数

calc = lambda n:n**n
print(calc(10))
View Code

匿名函数lambda主要和其他函数搭配使用

九、函数式编程

1.函数式编程就是一种抽象程度很高的编程范式,纯粹的函数式编程语言编写的函数没有变量,因此,任意一个函数,只要输入是确定的,输出就是确定的,这种纯函数我们称之为没有副作用。而允许使用变量的程序设计语言,由于函数内部的变量状态不确定,同样的输入,可能得到不同的输出,因此,这种函数是有副作用的。

函数式编程的一个特点是允许把函数本身作为参数传给另一个函数,还允许返回一个函数,因为Python允许使用变量,所以Python不是纯函数式编程语言。

2.高阶函数:可以接收另外一个函数做变量的函数

def add(x,y,f):
    return (f(x)+f(y))
print(add(-1,6,abs))
View Code

高阶函数满足两个特性:(1)传入参数是一个函数名;(2)返回值是一个函数名

3.map函数和reduce函数

(1)map函数接收两个参数,一个是函数,一个是可迭代对象

def f(x):
    return x*x
print(list(map(f,[1,2,3,4,5])))
L = []
for i in [1,2,3,4,5]:
    L.append(i*i)
print(L)
View Code

相同功能可以用for实现,但map函数把运算规则抽象了,可以计算任意复杂函数。

map函数结合匿名函数的使用

print(list(map(lambda x:x*x,range(5))))
View Code

(2)reduce函数把一个函数作用到一个序列[x1,x2,x3,...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积运算。

from functools import reduce
def f(x,y):
    return x*100+y*10
print(reduce(f,[1,2,3,4,5]))
View Code

4.filter函数

与map函数类似,filter函数也要接收一个函数和一个序列,filter函数把传入的函数依次作用于每一个元素,然后根据返回值是True和False来决定保留还是丢弃

def is_odd(x):
    return x % 2 == 1
print(list(filter(is_odd,[1,2,3,4,5,6,7,8])))
View Code

十、内置函数

 https://docs.python.org/3/library/functions.html?highlight=built#ascii 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325321024&siteId=291194637