1.python没有块级作用域,代码快里的变量,外部可以调用
1 if 1 ==1: 2 name = "qinyanli" 3 print(name) 4 5 for i in range(10): 6 age = i 7 print(age)
打印结果为:
qinyanli
9
2.python中的作用域分4种情况:
L:Local,局部作用域,函数中定义的变量
E:enclosing,嵌套的父级函数的局部作用域,即包含此函数的上级函数的局部作用域,但不是全局的。
G:global,全部变量,就是模块级别定义的变量
B:built-in。系统固定模块里面的变量。比如int,bytearray等。搜索变量的优先级顺序依次是:LEGB
1 x = int(2.5) #int 为built in 2 x = 10 #count = 10 global 全局作用域 3 def outer(): 4 x = 5 #x = 5 enclosing 作用域 5 def f(): 6 x = 3 #x= 3 local作用域 7 print (x)
3.局部作用域修改全局作用域,需要加上global +变量名
错误代码案例:
count = 10 def f(): print(count) count = 20 f()
运行之后报错:UnboundLocalError: local variable 'count' referenced before assignmen
正确代码案例:
count = 10 def f(): global count print(count) count = 20 f()
运行结果为:10
4.局部作用域修改enclosing作用域,需要加nonlocal+变量名
def outer(): count = 20 def f(): nonlocal count print(count) count = 5 f() outer()
运行结果为20