# 2.变量

```python
a = "dasdsa"
```

> 如上定义了变量a，并赋值。

* python变量的声明及定义，不需要指明变量的类型（当然python中变量是没有类型的），也不需要其他关键字表明定义一个变量（如swift 中的var）。
* 但是变量定义后必须赋值，不然没有任何意义，而且会报错，如下：

![](/files/-MjGncSDV-a3qCCwqB-d)

## 变量作用域

> python 的变量作用域由变量在哪里定义的决定，

* L （Local） 局部作用域
* E （Enclosing） 闭包函数外的函数中
* G （Global） 全局作用域
* B （Built-in） 内置作用域（内置函数所在模块的范围）

```python
g_count = 0  # 全局作用域
def outer():
    o_count = 1  # 闭包函数外的函数中
    def inner():
        i_count = 2  # 局部作用域
```

> 内置作用域是通过一个名为 builtin 的标准模块来实现的，但是这个变量名自身并没有放入内置作用域内，所以必须导入这个文件才能够使用它。

> Python 中只有模块（module），类（class）以及函数（def、lambda）才会引入新的作用域，其它的代码块（如 if/elif/else/、try/except、for/while等）是不会引入新的作用域的，也就是说这些语句内定义的变量，外部也可以访问

```python
if True:
   a = "123"
else
   b = "1234"
print(a)          # a 定义了且可以访问； 只有模块，类，函数可以引入新的作用域
print(b)          # b 没有定义，代码没有执行到

```

## 全局变量和局部变量

> 定义在函数内部的变量拥有一个局部作用域，定义在函数外的拥有全局作用域。

> 局部变量只能在其被声明的函数内部访问，而全局变量可以在整个程序范围内访问

```python

a = 11            # 全局变量
def func():
    print(a)      # 可以直接访问全局变量
func()

```

```python

a = 11            # 全局变量
def func():
    a = 12        # 定义局部变量     
    print(a)      # 这里a为局部变量
func()

```

```python

a = 11            # 全局变量
def func():   
    a = a + 1     # 这里会报错； 后面的a 是局部变量，但是没有被定义
    print(a)      
    
func()

```

![](/files/5EptuKQt07UjgxXH8TZS)

> 当内部作用域想修改外部作用域的变量时，就要用到global和nonlocal关键字了

```python

# 修改全局变量

a = 11            # 全局变量
def func():
    global a      # 声明这里的a 为全局变量a     
    a = a + 1
    print(a)      # 可以直接访问全局变量
func()

print(a)          # 这里a已经被修改



def func1():
    b = 11
    def func2():
        nonlocal b
        b = b + 1

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gitbook.existorlive.cn/kai-fa-yu-yan-xue-xi/python/2.-bian-liang.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
