Local variables and global variables for Python

Source: Internet
Author: User

In Python, there are some special places for referencing global variables. Let's look at the code example.

def Test (): ...      Print num ...      = num+1      ... Print Value ... >>> Test (12)

The above code defines a global variable, num, so we can use the global variable within the function.

But if we want to modify the global variables inside the function, the notation is special, such as:

def Test (): ...     Num=2      ... Print num ... >>> Test ()2>>> num1

As you can see, the num=2 operation inside the function does not operate on global variables, but instead produces a new local variable. has no effect on global variables.
In some cases, there will be an error, such as:

def Test (): ...     Num=num+1 ... >>> Test () Traceback (most recent call last):  '<stdin>'in  <module>  "<stdin>"in   ' Num ' referenced before assignment

From the information of the error, in the test function, Num still as a local variable, but because there is no assignment before the reference, so error.

To refer to global variables within a function, it is a good practice to refer to them first through the global keyword, such as:

def Test (): ...      Global num ...     Num=num+1      ... Print num ... >>> Test ()2>>> num2

As you can see, the Global keyword can be used within a function after it is identified.

Of course, we need to emphasize that, normally in application development, we should avoid using global variables, which is explained from a grammatical point of view.

Local variables and global variables for Python

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.