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