变量与常量 #

一、变量概述 #

变量是存储数据的容器。在Python中,变量不需要声明类型,直接赋值即可创建。

1.1 变量的本质 #

Python中的变量是对对象的引用(指针),变量名指向内存中的对象。

python
# 创建变量
x = 10
name = "Tom"
prices = [1.5, 2.5, 3.5]

# 变量存储的是对象的引用
a = [1, 2, 3]
b = a           # b和a指向同一个列表对象
b.append(4)
print(a)        # [1, 2, 3, 4] - a也变了

1.2 变量命名规则 #

规则 正确示例 错误示例
以字母或下划线开头 name, _count 1name, @var
只能包含字母、数字、下划线 user_name user-name, user name
不能使用关键字 my_class class, if, for
区分大小写 Namename -
python
# 合法的变量名
name = "Tom"
user_name = "Alice"
_private = "私有"
MAX_VALUE = 100

# 非法的变量名
# 1name = "错误"      # 以数字开头
# user-name = "错误"  # 包含连字符
# class = "错误"      # 使用关键字

1.3 命名风格 #

python
# snake_case:变量和函数(推荐)
user_name = "Tom"
total_price = 99.99
def get_user_info():
    pass

# camelCase:不推荐用于变量
userName = "Tom"  # 不推荐

# PascalCase:类名
class UserInfo:
    pass

# UPPER_CASE:常量
MAX_SIZE = 100
PI = 3.14159

二、变量赋值 #

2.1 基本赋值 #

python
# 单个变量赋值
x = 10
name = "Tom"

# 连续赋值(同一值)
a = b = c = 0
# 等价于
# a = 0
# b = 0
# c = 0

# 链式赋值
x = y = z = [1, 2, 3]  # 三个变量指向同一对象

2.2 多变量赋值 #

python
# 同时为多个变量赋不同值
a, b, c = 1, 2, 3
# a = 1, b = 2, c = 3

# 交换变量值(Python特有)
x, y = 1, 2
x, y = y, x  # x = 2, y = 1

# 用于函数返回多个值
def get_coordinates():
    return 10, 20

x, y = get_coordinates()

2.3 解包赋值 #

python
# 列表解包
numbers = [1, 2, 3]
a, b, c = numbers  # a=1, b=2, c=3

# 元组解包
point = (100, 200)
x, y = point  # x=100, y=200

# 字典解包(解包键)
person = {"name": "Tom", "age": 25}
key1, key2 = person  # key1="name", key2="age"

# 星号表达式(Python 3+)
numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
# first=1, middle=[2, 3, 4], last=5

head, *tail = [1, 2, 3, 4, 5]
# head=1, tail=[2, 3, 4, 5]

*init, last = [1, 2, 3, 4, 5]
# init=[1, 2, 3, 4], last=5

2.4 增量赋值 #

python
x = 10

# 加法赋值
x += 5   # x = x + 5 = 15

# 减法赋值
x -= 3   # x = x - 3 = 12

# 乘法赋值
x *= 2   # x = x * 2 = 24

# 除法赋值
x /= 4   # x = x / 4 = 6.0

# 整除赋值
x //= 2  # x = x // 2 = 3.0

# 取余赋值
x %= 2   # x = x % 2 = 1.0

# 幂运算赋值
x **= 3  # x = x ** 3 = 1.0

三、变量类型 #

3.1 动态类型 #

Python是动态类型语言,变量类型可以改变:

python
x = 10          # x是整数
print(type(x))  # <class 'int'>

x = "Hello"     # x变成字符串
print(type(x))  # <class 'str'>

x = [1, 2, 3]   # x变成列表
print(type(x))  # <class 'list'>

3.2 类型检查 #

python
# 使用type()
x = 10
print(type(x))      # <class 'int'>

# 使用isinstance()(推荐)
x = 10
print(isinstance(x, int))      # True
print(isinstance(x, (int, str)))  # True,检查多种类型

# 使用type()比较(不推荐)
print(type(x) == int)  # True,但不如isinstance灵活

3.3 类型转换 #

python
# 整数转换
int("123")      # 123
int(3.9)        # 3(截断)
int("1010", 2)  # 10(二进制转十进制)

# 浮点数转换
float("3.14")   # 3.14
float(10)       # 10.0

# 字符串转换
str(123)        # "123"
str(3.14)       # "3.14"
str([1, 2, 3])  # "[1, 2, 3]"

# 布尔转换
bool(1)         # True
bool(0)         # False
bool("")        # False
bool("hello")   # True

# 列表转换
list("hello")   # ['h', 'e', 'l', 'l', 'o']
list((1, 2, 3)) # [1, 2, 3]

# 元组转换
tuple([1, 2, 3])  # (1, 2, 3)

四、变量作用域 #

4.1 局部变量 #

python
def my_function():
    local_var = 10  # 局部变量
    print(local_var)

my_function()
# print(local_var)  # NameError: 局部变量不能在外部访问

4.2 全局变量 #

python
global_var = 100  # 全局变量

def my_function():
    print(global_var)  # 可以访问全局变量

my_function()
print(global_var)  # 100

4.3 global关键字 #

python
counter = 0

def increment():
    global counter  # 声明使用全局变量
    counter += 1

increment()
print(counter)  # 1

4.4 nonlocal关键字 #

python
def outer():
    count = 0
    
    def inner():
        nonlocal count  # 引用外层函数的变量
        count += 1
    
    inner()
    print(count)  # 1

outer()

五、常量 #

Python没有真正的常量,约定用全大写变量名表示常量。

5.1 常量定义 #

python
# 数学常量
PI = 3.14159
E = 2.71828

# 配置常量
MAX_SIZE = 100
MIN_SIZE = 1
DEFAULT_NAME = "Unknown"

# 状态常量
STATUS_OK = 200
STATUS_NOT_FOUND = 404
STATUS_ERROR = 500

5.2 常量的特点 #

python
PI = 3.14159

# 从语法上讲,常量可以被修改(但不要这样做!)
PI = 3.14  # 语法正确,但违反约定

# 建议使用注释提醒
# 以下为常量,请勿修改
PI = 3.14159

5.3 使用枚举类实现常量 #

python
from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

print(Color.RED)        # Color.RED
print(Color.RED.value)  # 1
print(Color.RED.name)   # 'RED'

六、变量删除 #

python
x = 10
print(x)  # 10

del x     # 删除变量
# print(x)  # NameError: name 'x' is not defined

# 删除列表元素
numbers = [1, 2, 3, 4, 5]
del numbers[2]  # 删除索引2的元素
print(numbers)  # [1, 2, 4, 5]

# 删除字典键值
person = {"name": "Tom", "age": 25}
del person["age"]
print(person)  # {'name': 'Tom'}

七、变量与内存 #

7.1 内存地址 #

python
x = 10
print(id(x))  # 查看内存地址,如:140234567890

a = 10
b = 10
print(id(a) == id(b))  # True,小整数被缓存

7.2 可变与不可变 #

python
# 不可变类型:int, str, tuple
x = 10
print(id(x))  # 地址A
x = 20
print(id(x))  # 地址B(新对象)

# 可变类型:list, dict, set
numbers = [1, 2, 3]
print(id(numbers))  # 地址C
numbers.append(4)
print(id(numbers))  # 地址C(同一对象)

7.3 深拷贝与浅拷贝 #

python
import copy

# 浅拷贝
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
shallow[0][0] = 999
print(original)  # [[999, 2], [3, 4]] - 被影响了

# 深拷贝
original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)
deep[0][0] = 999
print(original)  # [[1, 2], [3, 4]] - 不受影响

八、最佳实践 #

8.1 有意义的命名 #

python
# 好的命名
student_name = "Tom"
total_price = 99.99
is_valid = True
user_list = ["Tom", "Alice"]

# 不好的命名
x = "Tom"
tp = 99.99
iv = True
l = ["Tom", "Alice"]  # 容易与数字1混淆

8.2 避免魔法数字 #

python
# 不好
if score > 60:
    print("及格")

# 好
PASS_SCORE = 60
if score > PASS_SCORE:
    print("及格")

8.3 使用类型注解 #

python
# Python 3.6+ 类型注解
name: str = "Tom"
age: int = 25
price: float = 99.99
is_active: bool = True

def greet(name: str) -> str:
    return f"Hello, {name}"

def add(a: int, b: int) -> int:
    return a + b

九、总结 #

概念 要点
变量定义 直接赋值,无需声明类型
命名规则 字母/下划线开头,只能包含字母、数字、下划线
命名风格 snake_case变量,PascalCase类名,UPPER_CASE常量
动态类型 变量类型可变,使用type()或isinstance()检查
作用域 局部变量、全局变量,使用global/nonlocal关键字
常量 约定用全大写,可用Enum类实现真正的常量
最后更新:2026-03-16