Interpretation of local variables and global variables in Python

Source: Internet
Author: User

num = 5

def func ():

num + = 1

Print (num)

Print (num)

Output:unboundlocalerror:local variable ' num ' referenced before assignment

Translation: Local variable error: the variable "num" is not defined and is applied. This proves once again that a local variable is defined, not a global "num" that is used

Summary: When a variable already outside the function body has been defined as a global variable, it is re-assigned in the function body again, and then the variable is defined as a local variable in the function body, only in the function body will be effective. Restores a state that was not previously defined in the function body when it was outside the body of the function.

def func ():

num = 10

Print (num)

Func ()

Print (num)

Output:nameerror:name ' num ' is not defined

Name error: Variable num is not defined

This means that NUM is defined as a local variable and is valid only within the function body.

num = 100

def func ()

x = num +100

Print (x)

Output: 200

This means that num is used as a global variable.

Summary: See the program Yourself

If you want to define a global variable within a function body, you can define it with Globa, as follows:

num = 100

def func ():

Global num

num = 200

Print (num)

Func ()

Print (num)

Output: 200

Output: 200

This indicates that NUM is used as a global variable.

Interpretation of local variables and global variables in Python

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.