# python教程之全局与局部变量

## 局部变量(Local Variable)

```>>> def func1():       # 定义函数，名称为func1
number = 1           # 定义变量，名称为number
print(number)

>>> print(number)
Traceback (most recent call last):
File "<pyshell#61>", line 1, in <module>
print(number)
NameError: name 'number' is not defined
>>>
```

## 全局变量(Global Variable)

```>>> number2 = 10                  #  定义全局变量
>>> def func2():                  # 定义函数
number3 = number2 + 10    # 定义局部变量，同时赋值
print(number3)

>>> number2
10
>>> number3
```

```>>> number2 = 10               # 定义全局变量
>>> def double():                # 定义函数
global number2            # 申明number2为全局变量
number2 = number2 * 2

>>> double()
>>> number2
20
>>>
```

```>>> number3 = 0               # 定义全局变量
>>> def double():               # 定义函数
number3 = number3 * 2       # 试图修改变量的值

>>> double()
Traceback (most recent call last):
File "<pyshell#86>", line 1, in <module>
double()
File "<pyshell#85>", line 2, in double
number3 = number3 * 2
UnboundLocalError: local variable 'number3' referenced before assignment
>>>
```

```>>> number5 = 10           # 定义全局变量
>>> def test1():           # 定义函数test1
number5 = 20             # 定义局部变量
print(number5)

>>> test1()
20
>>> number5               # number5的值并没有改变
10
```

## nonlocal变量(nonlocal Variable)

```>>> def zsum(x,y):
z = x + y
def func():          # 在函数中又定义了一个函数
nonlocal z   # 申明z为nonlocal变量
z = z * 2
func()               # 调用func函数
print(z)             # 打印z的值

>>> zsum(3,7)
20
```