变量

python/variable2026-08-24 19:46:25

变量 是用于存储数据的命名位置。

变量可以存储各种类型的数据,包括数字、字符串、列表、字典等。

变量的命名

变量有自己的名字,称为 变量名。

变量名应遵循标识符命名规则:只能包含字母、数字和下划线,不能以数字开头,区分大小写。

不能使用 Python 的关键字作为变量名。

变量的定义

变量不需要显式声明,直接使用 = 赋值即可创建变量。

x = 10
name = "Alice"
is_active = True

变量类型

Python 是动态类型语言,变量的类型在运行时确定,并且通过赋值等操作可以改变。

可以使用 type() 函数查看变量的类型。

x = 10
print(type(x))  # 输出: <class 'int'>

name = "Alice"
print(type(name))  # 输出: <class 'str'>

变量的赋值

在定义后,变量可以在其生命周期内多次赋值,且可以改变类型。

x = 10
print(x)  # 输出: 10

x = "Hello"
print(x)  # 输出: Hello

可以在一行中同时为多个变量赋值。

a, b, c = 1, 2, 3
print(a, b, c)  # 输出: 1 2 3

# 交换变量的值
a, b = b, a
print(a, b)  # 输出: 2 1

变量作用域

  • 全局变量在函数外部定义,作用域为整个程序。
  • 局部变量在函数内部定义,作用域仅限于函数内部。
global_var = "I am global"

def my_function():
    local_var = "I am local"
    print(global_var)  # 可以访问全局变量
    print(local_var)   # 输出: I am local

my_function()
print(global_var)  # 输出: I am global
# print(local_var)  # 这行会报错,因为 local_var 是局部变量,函数外部无法访问

global 关键字

在函数内部修改全局变量时,需要使用 global 关键字。

count = 0

def increment():
    global count
    count += 1

increment()
print(count)  # 输出: 1

nonlocal 关键字

在嵌套函数中修改外层(但不是全局)变量时,需要使用 nonlocal 关键字。

def outer_function():
    outer_var = "outer"

    def inner_function():
        nonlocal outer_var
        outer_var = "inner"

    inner_function()
    print(outer_var)  # 输出: inner

outer_function()

本页目录