Python中的函数问题
一 函数是什么?
概述
编程中的函数在不同的编程语言中也有很多不同的叫法。在C语言中只有function,在Java里面叫做method。函数能提高应用的模块性和代码的重复利用率。Python提供了许多内建函数,但也可以自己创建函数,这被叫做用户自定义函数。
定义
函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可。
特性
1.代码重用
2.保持一致性
3.可扩展性
二 函数的创建
格式
Python 定义函数使用 def 关键字,一般格式如下:
def 函数名(参数列表):
函数体
def hello():
print('hello')
hello()#调用
函数名的命名规则:
函数名必须以下划线或字母开头,可以包含任意字母、数字或下划线的组合,不能使用任何的标点符号。
函数名是区分大小写的。
函数名不能是保留字。
形参和实参
形参:形式参数,不是实际存在,是虚拟变量。在定义函数和函数体的时候使用形参,目的是在函数调用时接收实参(实参个数,类型应与实参一一对应)
实参:实际参数,调用函数时传给函数的参数,可以是常量,变量,表达式,函数,传给形参 。
区别:形参是虚拟的,不占用内存空间,形参变量只有在被调用时才分配内存单元,实参是一个变量,占用内存空间,数据传送单向,实参传给形参,不能形参传给实参
import time
times=time.strftime('%Y--%m--%d')
def f(time):
print('Now time is : %s'%times)
f(times)
三 函数的参数
必需参数
关键字参数
默认参数
不定长参数
必需的参数:
必需参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样。
def f(name,age):
print('I am %s,I am %d'%(name,age))
f('hongsong',18)
f('yangyang',16)
关键字参数:
关键字参数和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值。使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值。
def f(name,age):
print('I am %s,I am %d'%(name,age))
# f(16,'alvin') #报错
f(age=16,name='alvin')
缺省参数(默认参数):
调用函数时,缺省参数的值如果没有传入,则被认为是默认值。如果sex没有被传入,下例会打印默认的sex
def print_info(name,age,sex='male'):
print('Name:%s'%name)
print('age:%s'%age)
print('Sex:%s'%sex)
return
print_info('alex',18)
print_info('铁锤',40,'female')
不定长参数
你可能需要一个函数能处理比当初声明时更多的参数。这些参数叫做不定长参数,和上述2种参数不同,声明时不会命名。
def add(*tuples):
sum=0
for v in tuples:
sum+=v
return sum
print(add(1,4,6,9))
print(add(1,4,6,9,5))
加了星号(*)的变量名会存放所有未命名的变量参数。而加(**)的变量名会 存放命名的变量参数
def print_info(**kwargs):
print(kwargs)
for i in kwargs:
print('%s:%s'%(i,kwargs[i]))#根据参数可以打印任意相关信息了
return
print_info(name='alex',age=18,sex='female',hobby='girl',nationality='Chinese',
ability='Python')
def print_info(name,*args,**kwargs):#def print_info(name,**kwargs,*args):报错
print('Name:%s'%name)
print('args:',args)
print('kwargs:',kwargs)
return
print_info('alex',18,hobby='girl',nationality='Chinese',ability='Python')
参数位置:非默认参数–>默认参数–>不命名参数–>命名参数
高阶函数:
接受函数为参数,或者把函数作为结果返回的函数是高阶函数。例如:
def add(x,y,f):
return f(x) + f(y)
res = add(3,-6,abs)
print(res)
def foo():
x=3
def bar():
return x
return bar
四 函数的返回值
要想获取函数的执行结果,就可以用return语句把结果返回。
注意:
- 函数在执行过程中只要遇到return语句,就会停止执行并返回结果,也可以理解为 return 语句代表着函数的结束。
- 如果未在函数中指定return,那这个函数的返回值为None。
- 如果return多个对象,解释器会把这多个对象组装成一个元组作为一个整体结果输出。
五 函数作用域
python中的作用域分4种情况:
L:local,局部作用域,即函数中定义的变量;
E:enclosing,嵌套的父级函数的局部作用域,即被包含的函数的上级函数的局部作用域,但不是全局的;
G:global,全局变量,就是模块级别定义的变量;
B:built-in,系统固定模块里面的变量,比如int, bytearray等。
搜索变量的优先级顺序依次是:作用域局部>外层作用域>当前模块中的全局>python内置作用域,也就是LEGB。
x = int(2.9) # int built-in
g_count = 0 # global
def outer():
o_count = 1 # enclosing
def inner():
i_count = 2 # local
print(o_count)
# print(i_count) 找不到
inner()
outer()
# print(o_count) #找不到
当然,local和enclosing是相对的,enclosing变量相对上层来说也是local。
作用域产生
在Python中,只有模块(module),类(class)以及函数(def、lambda)才会引入新的作用域,其它的代码块(如if、try、for等)是不会引入新的作用域的,如下代码:
if 2>1:
x = 1
print(x) # 1
这个是没有问题的,if并没有引入一个新的作用域,x仍处在当前作用域中,后面代码可以使用。
def test():
x = 2
print(x) # NameError: name 'x' is not defined
def、class、lambda是可以引入新作用域的。
变量的修改
x=6
def f2():
print(x)
x=5
f2()
# 错误的原因在于print(x)时,解释器会在局部作用域找,会找到x=5(函数已经加载到内存),但x使用在声明前了,所以报错:
# local variable 'x' referenced before assignment.如何证明找到了x=5呢?简单:注释掉x=5,x=6
# 报错为:name 'x' is not defined
global关键字
当内部作用域想修改外部作用域的变量时,就要用到global和nonlocal关键字了,当修改的变量是在全局作用域(global作用域)上的,就要使用global先声明一下,代码如下:
count = 10
def outer():
global count
print(count)
count = 100
print(count)
outer()
nonlocal关键字
global关键字声明的变量必须在全局作用域上,不能在嵌套作用域上,当要修改嵌套作用域(enclosing作用域,外层非全局作用域)中的变量怎么办呢,这时就需要nonlocal关键字了。
def outer():
count = 10
def inner():
nonlocal count
count = 20
print(count)
inner()
print(count)
outer()
小结
(1)变量查找顺序:LEGB,作用域局部>外层作用域>当前模块中的全局>python内置作用域;
(2)只有模块、类、及函数才能引入新作用域;
(3)对于一个变量,内部作用域先声明就会覆盖外部变量,不声明直接使用,就会使用外部作用域的变量;
(4)内部作用域要修改外部作用域变量的值时,全局变量要使用global关键字,嵌套作用域变量要使用nonlocal关键字。nonlocal是python3新增的关键字,有了这个 关键字,就能完美的实现闭包了。
六 递归函数
定义: 在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。
递归函数的优点: 是定义简单,逻辑清晰。理论上,所有的递归函数都可以写成循环的方式,但循环的逻辑不如递归清晰。
递归特性:
- 必须有一个明确的结束条件
- 每次进入更深一层递归时,问题规模相比上次递归都应有所减少
- 递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返 回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出。)
七 内置函数(Py3.7)
Built-in Functions(内置函数)
abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
重要的内置函数:
'''
重要的内置函数 filter()
"""
filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
"""
'''
str_1 = ['a','b','c','d']
def fun_1(s):
if s != 'a':
return s
result_1 = filter(fun_1,str_1)
print(list(result_1))#['b', 'c', 'd']
'''
重要的内置函数 map()
map(func, *iterables) --> map object
Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
'''
str_2 = ['a','b','c']
def fun_2(s):
return s +'hongsong'
result_2 = map(fun_2,str_2)
print(list(result_2))#['ahongsong', 'bhongsong', 'chongsong']
'''
重要的内置函数 reduce()
"""
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
"""
'''
from functools import reduce
def add_1(x,y):
return x + y
print(reduce(add_1,range(1,6)))#((((1+2)+3)+4)+5)---->15
匿名函数 lambda
普通函数与匿名函数的对比:
#普通函数
def add(a,b):
return a + b
print add(2,3)
#匿名函数
add = lambda a,b : a + b
print add(2,3)
匿名函数的命名规则,用lamdba 关键字标识,冒号(:)左侧表示函数接收的参数(a,b) ,冒号(:)右侧表示函数的返回值(a+b)。因为lamdba在创建时不需要命名,所以,叫匿名函数