Global variables and local variables for functions in Python

Source: Internet
Author: User

1. What is a local variable

A local variable is a variable that has a local effect and is defined inside a function. The scope is only within the function, the variables outside the function is not affected, that is, the same name function, if not in the function to do the global Declaration

Then there's no effect on the outside of the function.

1x ="Alex"2 3 deffunc (x):4     Print('the value of x is', X)5x = "A"6     Print('local variable x is changed to', X)7 8 func (x)9 Print('the value of x does not change and remains', X)Ten  One  A #The output is as follows - the value of X is Alex. - local variable x changed to a theThe value of x has not changed, still Alex.

2, what is the global variable, is the scope of coverage to the global, if the function inside the global declaration, then you can change the value of the global variable inside the function

1x ="Alex"2 3 deffunc ():4     Globalx5     Print('the value of the global variable x is', X)6x ="a"7     Print('global variable x is changed to', X)8 9 func ()Ten Print('the value of x now is', X) One  A #Output - the value of global variable x is Alex - global variable x changed to a theX Now the value is a

Global variables and local variables for functions 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.