- Python Data Structures and Algorithms
- Benjamin Baka
- 231字
- 2021-07-09 19:44:58
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.
- Vue.js前端開發(fā)基礎(chǔ)與項(xiàng)目實(shí)戰(zhàn)
- Programming ArcGIS 10.1 with Python Cookbook
- 深入淺出Android Jetpack
- TypeScript實(shí)戰(zhàn)指南
- 自制編程語言
- Instant Nancy Web Development
- Go語言精進(jìn)之路:從新手到高手的編程思想、方法和技巧(2)
- 編寫高質(zhì)量代碼:改善Objective-C程序的61個(gè)建議
- PHP與MySQL權(quán)威指南
- 微前端設(shè)計(jì)與實(shí)現(xiàn)
- PHP項(xiàng)目開發(fā)全程實(shí)錄(第4版)
- 虛擬現(xiàn)實(shí)建模與編程(SketchUp+OSG開發(fā)技術(shù))
- SAS編程演義
- 優(yōu)化驅(qū)動(dòng)的設(shè)計(jì)方法
- JavaScript程序設(shè)計(jì)實(shí)例教程(第2版)