Python global variables and local variables

Source: Internet
Author: User

Global variables and local variables

Variables defined inside a function have a local scope, which defines the owning global scope outside of the function .
Local variables can only be accessed within their declared functions, while global variables are accessible throughout the program. When a function is called, all variable names declared within the function are added to the scope. The following example:

total = 0; # 这是一个全局变量# 可写函数说明def sum( arg1, arg2 ):    #返回2个参数的和."    total = arg1 + arg2; # total在这里是局部变量.    #在函数中 如果对一个和全局变量名相同的变量进行=value的时候,默认是定义一个变量    #只不过这个变量的名字和全局变量的名字相同罢了    print ("函数内是局部变量 : ", total)    return total;#调用sum函数sum( 10, 20 );print ("函数外是全局变量 : ", total)

The result of the above example output:

Inside the function is a local variable: 30
Outside the function is a global variable: 0

Global and nonlocal keyword global

The Global and nonlocal keywords are used when the internal scope wants to modify the variables of the outer scope.

The following instance modifies the global variable num:

num = 1def fun1():    global num  # 使用global用来对一个全局变量的声明,那么这个函数中的num就不是定义一个局部变量,而是                #对全局变量进行修改    print(num)     num = 123    print(num)fun1()

The result of the above example output:
1
123

The list is when the global variable
As the following example

nums = [11,22,33]infor = {"name":"wang"}def test():    #for num in nums:    #    print(num)    nums.append(44)    infor['age'] = 18def test2():    print(nums)    print(infor)test() #[11, 22, 33, 44]test2() #{'name': 'wang', 'age': 18}
Nonlocal

If you want to modify a variable in a nested scope (enclosing scope, outer non-global scope) You need to nonlocal the keyword, as in the following example:

def outer():    num = 10    def inner():        nonlocal num   # nonlocal关键字声明        num = 100        print(num)    inner()    print(num)outer()

The result of the above example output:
100
100

There is also a special case where the following code is assumed to be running:

a = 10def test():    a = a + 1    print(a)test()

The above procedure executes, the error message is as follows:

Traceback (most recent call last):  File "test.py", line 7, in <module>    test()  File "test.py", line 5, in test    a = a + 1UnboundLocalError: local variable 'a' referenced before assignment

The error message is a local scope reference error because a in the test function uses a local, undefined, and cannot be modified .

Python global variables and local variables

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.