Scope of the Python variable

Source: Internet
Author: User
Tags variable scope

Variable scope:

In general, variables defined in the function body are called global variables, and variables defined in the function body are called local variables.

When a function is called, it usually reads its own local variable before reading the global variable.

You can access global variables within a function, but to modify global variables, you need certain conditions:

If the global variable is a mutable data type , you can modify it directly:

DIC = {0:0, 1:1, 2:2}def F ():    dic[3] = 3f () print dic>>{0:0, 1:1, 2:2, 3:3}

If the global variable is an immutable data type , or you want to re-assign a value to a mutable data type :

You need to use the Global keyword

  

LST = [1,2,3]def f ():    lst = ' hehe '    print lstf () print lst>> ' hehe ' >> [[+]

LST = [1,2,3]def f ():    global lst    lst = ' hehe '    print lstf () print lst>> ' hehe ' >> ' hehe '

That is, lists and dictionaries can be modified directly within the function;

To re-assign a value, you need to use the Global keyword. (Immutable data types such as String, Integer, tuple, modify = = Assignment)

Scope of the Python variable

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.