python3.6.2 local variable def

Source: Internet
Author: User
Tags function definition

When you declare variables within a function definition, they are not related to other variables with the same name outside the function, that is, the variable name is local to the function. This is called the scope of the variable. All variables are scoped to their defined blocks, starting with the point where their names are defined.

Using local variables

def func (x):
Print (' x is ', x)
x=2
Print (' Changed local x to ', X)
X=50
Func (x)
Print (' x is still ', X)

Output

X is 50
Changed local X to 2
X is still 50

How it works

In the function, the first time we use the value of X, Python uses the value of the formal parameter declared by the function. Next, we assign the value 2 to X. X is the local variable of the function. So, when we change the value of x within a function, the x defined in the main block is unaffected. In the last print statement, we proved that the X value in the main block is really not affected.

python3.6.2 local variable def

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.