CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day16-20/code/example11.py
Views: 729
1
"""
2
变量的作用域以及Python搜索变量的顺序
3
LEGB: Local --> Embedded --> Global --> Built-in
4
global - 声明或定义全局变量(要么直接使用现有的全局作用域的变量,要么定义一个变量放到全局作用域)
5
nonlocal - 声明使用嵌套作用域的变量(如果嵌套作用域没有对应的变量直接报错)
6
"""
7
x = 100
8
9
10
def foo():
11
global x
12
x = 200
13
14
def bar():
15
x = 300
16
print(x)
17
18
bar()
19
print(x)
20
21
22
foo()
23
print(x)
24
25