The variable scope problem of Python

Source: Internet
Author: User
Tags variable scope

Accidentally fell into a hole. Carefully analyzed the following reasons. It turns out to be a variable scope problem. The simple abstraction is as follows:

id=1# many line codes [ID for ID in range] #许多行代码if id!=1:    #做一些事情    passelse:    #做另外一些事情

As a result, the ID

[ID for ID in range (10)]

has been affected by the change, leading to the production of insect pests.

The next variable scope is explored, and the conclusion is as follows:

1. A variable with the same name in the function does not affect the variable with the same name outside the function (if any adornments are added-for example, global)

Id=1def Test ():    id=2print id#===1

2. The minimum scope of a variable is a function. Inside the function, the function of the variable is from the beginning to the end. (This differs from other languages)

id = 1if True:    id=2print id#===2id = 1for i in range:    id=iprint i#====9

Also the following is OK:

If True:    b=1print B

Output 1, does not become a local temporary code block variable because B is under If/for/while!

The minimum scope of a variable is a function, or even an extreme point, and the following is also output 1:

For I in range: for J in    Range (2): If true: If true:                    c=1print C

  

The variable scope problem of 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.