函数

>>> count = 5                    #global关键字,函数中去修改全局变量

>>> def myfun():

count = 10

print(10)


>>> myfun()

10

>>> print(count)

5

>>> def myfun():

global count

count = 10

print(10)


>>> myfun()

10

>>> print(count)

10

>>> def fun1():                     #内嵌函数,允许函数内部创建另一个函数

print('fun1()正在被调用...')

def fun2():

print('fun2()正在被调用...')

fun2()


>>> fun1()

fun1()正在被调用...

fun2()正在被调用...

>>> def funX(x):                     #闭包

def funY(y):

return x * y

return funY


>>> i = funX(8)

>>> i

.funY at 0x032B9A98>

>>> type(i)

>>> i(5)

40

>>> funX(8)(5)

40

>>> def fun1():                     #nonlocal关键字

x = 5

def fun2():

nonlocal x

x *= x

return x

return fun2()


>>> fun1()

25