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 local variables and global variables .
So called local variables , It refers to the variables defined in the function , Can only be used within a function , It has nothing to do with other variables with the same name outside the function . In different functions , You can use local variables with the same name , They represent different objects , Mutual interference . Besides , The formal parameters of a function also belong to local variables , The scope is limited to the inside of the function .
Variables defined outside the function are called global variables , Global variables are valid throughout the program .
example : Analyze the running results of the following programs .
total = 0 # Global variables total
def sum( arg1, arg2 ): # return 2 The sum of parameters
total = arg1 + arg2 # local variable total
print (" Function is a local variable : ", total) # Output local variable total Value
return total
sum(10, 20) # call sum function
print (" Outside the function is the global variable : ", total) # Output global variables total Value
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 Knowledge about local and global variables of function , 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 .