What is the namespace and scope of Python functions
This article mainly introduces what is the namespace and scope of Python functions. It is very detailed and has a certain reference value. Friends who are interested must finish it!
1.Local scope a = 100def func5 (): B = 50 a = 99 print ('within the function, a) print (' within the function, b) print ('outside the function, a) func5 () print (' outside the function, b)
Return the result:
Outside the function a 100
Within the function a 99
Within the function b 50
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/python knowledge Summary / 2.python self-study Network-General Module-Video Source Code / test.py", line 12, in
Print ('outside the function, b)
NameError: name 'b'is not defined
The b variable is defined in the above function, so it cannot be output outside.
2.Enclosing function locals scope a = 100def func5 (): B = 50 print ('intra-function, a) print (' intra-function, b) def func6 (): print ('lower-level function, a) print (' lower-level function, b) func6 () func5 ()
Return the result:
A 100 within the function
Within the function b 50
Within the lower level function a 100
Within the lower level function b 50
3.Global global variable a = 123def func (): a = 100print (a) print (a) func (a) print (a) print (a) = 123def func (): global a # cannot use nonlocal a = 100print (a) print (locals ()) # View the local variable print (globals ()) # look at the global variable print (a) func () print (a) 4. The nonlocal variable nonlocaldef func5 (): B = 50 print (b) def func6 (): nonlocal b # is nonlocal and only applies to the interior of the closure b = 60 print (b) func6 () print (b) func5 () 5. The nearest principle b = 1111def func5 (): B = 50 print (b) def func6 (): B = 60 print (b) # where b finds func6 () print (b) func5 () a = 100def func5 (): B = 50 print (a) print (b) def func6 (): B = 60 print (b) print (a) func5 () 6. Function execution order a = 123def func1 (): print (a) print (b) func1 () # cannot print bb = 456func1 () # can print b7. If True: a = 100print (a) for i in range (1,10): print (I) print (I)
There is no scope in the loop code block.
These are all the contents of the article "what is the namespace and scope of Python functions?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!