1、内置函数
错误示例:
>>> def Fun1():
x=5
def Fun2():
x*=x
return x
return Fun2()
>>> Fun1()
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
Fun1()
File "<pyshell#9>", line 6, in Fun1
return Fun2()
File "<pyshell#9>", line 4, in Fun2
x*=x
UnboundLocalError: local variable 'x' referenced before assignment
说明:Fun2()里面的x相对于Fun1()来说,是局部变量。
解决方法:
(1)可以将x变为列表,因为列表并不存放在栈里面,所以不存在全部变量和局部变量的区别。
>>> def Fun1():
x=[5]
def Fun2():
x[0]*=x[0]
return x[0]
return Fun2()
>>> Fun1()
25
(2)将Fun2()里面的x使用关键字nonlocal声明为全局变量:
>>> def Fun1():
x=5
def Fun2():
nonlocal x
x*=x
return x
return Fun2()
>>> Fun1()
25
2、闭包
格式:函数名 = lambda 参数列表 : 函数表达式
>>> g = lambda x,y:x*y
>>> g(2,5)
10
说明:lambda表达式简化了代码的命名,增强了代码的可读性,使用起来更方便。