Python 2-2 function variable scope

Variable scope

Generally speaking, in a programming language, the scope of variables can be seen from small to large levels such as block level, function, class, module, package, etc. from the code structure. But in Python, there is no block-level scope, that is, if statement blocks, for statement blocks, with context managers, etc., there is no scope concept, they are equivalent to ordinary statements.

if True:            # if语句块没有作用域
    x = 1   
print(x)

def func():         # 函数有作用域
    a = 8  

print(a)
NameError: name 'a' is not defined

Usually, the code inside the function can access the external variables, but the external code usually cannot access the internal variables.

The scope of Python has 4 layers, namely:

  • L (Local) local scope
  • E (Enclosing) in the function outside the closure function
  • G (Global) global scope

Guess you like

Origin blog.csdn.net/weixin_43955170/article/details/112771801