About bloggers : Former Internet manufacturer tencent staff , Network security giant Venustech staff , Alibaba cloud development community expert blogger , WeChat official account java Quality creators of basic notes ,csdn High quality creative bloggers , Entrepreneur , Knowledge sharers , Welcome to your attention , give the thumbs-up , Collection .
In the actual development process , You will often encounter many identical or very similar operations , At this time , Code that implements similar operations can be encapsulated as functions , Then call the function where you need it . This can not only realize code reuse , It can also make the code more organized , Increase code reliability . Now let's introduce python Function of global and nonlocal Keyword related content .
When an internal scope wants to use variables from an external scope , You can use global and nonlocal keyword .
When modifying a variable defined outside a function inside a function , To be used global Keyword explicitly declares variables . Pass through... Inside the function global Keyword to declare or define global variables , It can be divided into two situations :
(1) A variable has been defined outside the function , If you need to use the value of the variable or modify the value of the variable in the function , And reflect the modified result outside the function , You can use keywords in functions global Explicitly declare the global variable .
(2) Use directly inside the function global Keyword to declare a variable as a global variable , If the global variable is not defined outside the function , After calling this function , Will create a new global variable .
example : Analyze the running results of the following programs .
num = 1
def fun():
global num # Use global Keyword declares a variable as a global variable
num += 1
print(' Within the function num The value of is ',num)
fun()
print(' Out of function num The value of is ',num)
give the result as follows .
If you want to modify variables in a nested scope in a nested function , You must use nonlocal keyword .
example : Analyze the running results of the following programs .
def outer():
num = 1
def inner():
nonlocal num #nonlocal Keyword declaration
num = 2
print(' inner Function num The value of is ',num)
inner()
print(' outer Function num The value of is ',num)
outer()
give the result as follows .
1、 Liao Xuefeng's official website
2、python Official website
3、Python Programming case tutorial
The above is about Python Function of global and nonlocal Keyword related knowledge , You can refer to it , If you think it's good , Welcome to thumb up 、 Collection 、 Looking at , Welcome to wechat search java Basic notes , Relevant knowledge will be continuously updated later , Make progress together .