官术网_书友最值得收藏!

Variable scope

It is important to understand the scoping rules of variables inside functions. Each time a function executes, a new local namespace is created. This represents a local environment that contains the names of the parameters and variables that are assigned by the function. To resolve a namespace when a function is called, the Python interpreter first searches the local namespace (that is, the function itself) and if no match is found, it searches the global namespace. This global namespace is the module in which the function was defined. If the name is still not found, it searches the built-in namespace. Finally, if this fails then the interpreter raises a NameError exception. Consider the following code:

    a=10; b=20 
def my_function():
global a
a=11; b=21
my_function()
print(a) #prints 11
print(b) #prints 20

Here is the output of the preceding code:

In the preceding code, we define two global variables. We need to tell the interpreter, using the keyword global, that inside the function, we are referring to a global variable. When we change this variable to 11, these changes are reflected in the global scope. However, the variable b we set to 21 is local to the function, and any changes made to it inside the function are not reflected in the global scope. When we run the function and print b, we see that it retains its global value.

主站蜘蛛池模板: 西贡区| 津南区| 望城县| 凭祥市| 密云县| 安溪县| 龙游县| 芜湖县| 游戏| 凌海市| 望江县| 霍山县| 东平县| 新野县| 临邑县| 大冶市| 铜陵市| 阳曲县| 历史| 曲松县| 元江| 天全县| 丹江口市| 太保市| 拜城县| 云阳县| 余干县| 股票| 重庆市| 长宁区| 大姚县| 灵璧县| 洛浦县| 昌乐县| 航空| 渑池县| 渭南市| 福清市| 无棣县| 武定县| 运城市|