- 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.
- R語言編程指南
- oreilly精品圖書:軟件開發(fā)者路線圖叢書(共8冊)
- Animate CC二維動畫設(shè)計(jì)與制作(微課版)
- JavaScript從入門到精通(第3版)
- Rust Essentials(Second Edition)
- 編程數(shù)學(xué)
- Learning Laravel's Eloquent
- Building Serverless Web Applications
- Machine Learning With Go
- 零基礎(chǔ)C#學(xué)習(xí)筆記
- 微信公眾平臺開發(fā)最佳實(shí)踐
- ASP.NET jQuery Cookbook(Second Edition)
- SQL Server 2014數(shù)據(jù)庫設(shè)計(jì)與開發(fā)教程(微課版)
- Python深度學(xué)習(xí)入門:從零構(gòu)建CNN和RNN
- Testing Practitioner Handbook