本文深入讲解Python中的变量定义、命名规则、各类数据类型及其操作,适合初学者系统学习。


目录

  1. 变量的本质与命名规则
  2. 基本数据类型
  3. 复合数据类型
  4. 类型转换与检查
  5. 变量作用域
  6. 实际应用示例

1. 变量的本质与命名规则

1.1 什么是变量?

变量是指向内存中数据的标签。在Python中,变量不需要声明类型,赋值即创建。

# 变量赋值本质
x = 10      # 创建整数对象10,让x指向它
y = x       # y也指向同一个对象(不是复制值!)
x = 20     # x现在指向新对象20,y仍然指向10

1.2 命名规则

规则说明示例
必须由字母/下划线开头不能以数字开头name1 ✔️, 1name
区分大小写AgeageName vs name
不能使用保留字if, for, classclass_ ✔️(加下划线绕过)
约定:下划线命名全小写+下划线分隔user_name, total_count
约定:常量全大写不修改的变量PI = 3.14159, MAX_SIZE

保留字列表

import keyword
print(keyword.kwlist)
# ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', ...]

2. 基本数据类型

2.1 数字类型 (Numbers)

整数 (int)

# 不同进制表示
decimal = 100        # 十进制
binary = 0b1100100   # 二进制 (等于100)
octal = 0o144          # 八进制 (等于100)
hexadecimal = 0x64     # 十六进制 (等于100)

# 大数字可读性(Python 3.6+)
million = 1_000_000    # 下划线分隔,值为1000000

# 常用操作
abs(-10)             # 绝对值: 10
divmod(17, 5)        # 商和余数: (3, 2)
pow(2, 3)            # 幂运算: 8

浮点数 (float)

f1 = 3.14159
f2 = 2.5e2          # 科学计数法,等于250.0
f3 = float('inf')      # 无穷大

# 精度问题(重要!)
print(0.1 + 0.2)       # 0.30000000000000004,不是0.3!

# 解决方案:使用decimal模块
from decimal import Decimal, getcontext
getcontext().prec = 6  # 设置全局精度
price = Decimal('0.1') + Decimal('0.2')  # Decimal('0.300000')

复数 (complex)

c = 3 + 4j              # 实部3,虚部4
c.real                  # 3.0
c.imag                  # 4.0
abs(c)                   # 5.0 (模长,sqrt(3²+4²))
c.conjugate()           # (3-4j) 共轭复数

2.2 字符串 (str)

# 创建方式
s1 = '单引号'
s2 = "双引号,可包含'单引号'"
s3 = '''多行
字符串
支持换行'''

# 转义字符
print("行1\n行2")      # 换行
print("制表\t符")        # 制表
print("反斜杠\\")        # 反斜杠
print(r"原始字符串\n不转义")   # r前缀

# 字符串操作(索引与切片)
text = "Python"
print(text[0])          # 'P'(正向索引)
print(text[-1])         # 'n'(反向索引)
print(text[0:4])        # 'Pyth'(切片,不含结束索引)
print(text[::2])        # 'Pto'(步长2)
print(text[::-1])       # 'nohtyP'(反转!)

# 常用方法
text.upper()           # 'PYTHON'
text.lower()           # 'python'
text.startswith('Py')  # True
text.find('th')         # 2(索引位置)
text.replace('P', 'J')  # 'Jython'
"-".join(["a", "b", "c"])    # 'a-b-c'

2.3 布尔值 (bool)

flag = True              # 首字母大写
empty = bool("")       # False(空字符串为假)
zero = bool(0)          # False
none_bool = bool(None)  # False
collection = bool([1,2,3])  # True(非空容器为真)

# 布尔运算
True and False       # False
True or False         # True
not True             # False

2.4 空值 (NoneType)

result = None            # 表示"无"或"未定义"

# 与null的区别
print(None == 0)     # False
print(None == "")   # False
print(None == False) # False
print(result is None)  # True(推荐用is判断None)

3. 复合数据类型

3.1 列表 (list) - 有序可变

# 创建
fruits = ["apple", "banana", "cherry"]
mixed = [1, "two", 3.0, [4, 5], {"six": 6}]  # 可混合类型

# 增删改查
fruits.append("date")           # 末尾添加
fruits.insert(1, "apricot")      # 指定位置插入
fruits.extend(["fig", "grape"])   # 批量添加
fruits.remove("banana")          # 删除首个匹配项
popped = fruits.pop()            # 删除并返回末尾元素
fruits.pop(2)                    # 删除索引2处元素
fruits[0] = "avocado"             # 修改元素

# 高级操作
# 列表推导式(高性能写法)
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]

# 嵌套列表(矩阵)
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print(matrix[1][2])    # 访问:6

# 深浅拷贝(关键概念!)
import copy
original = [[1, 2], [3, 4]]
shallow = original.copy()      # 或 list(original)
deep = copy.deepcopy(original)    # 完全独立副本

shallow[0][0] = 999
print(original)               # [[999, 2], [3, 4]] - 变了!
print(deep)                     # [[1, 2], [3, 4]] - 没变

3.2 元组 (tuple) - 有序不可变

# 创建
coords = (10, 20)
single = (42,)               # 单元素逗号不能省!
empty_tuple = ()              # 空元组

# 不可变意味着什么?
coords[0] = 15                  # TypeError! 不能修改

# 但内部可变对象可以修改
nested = ([1, 2], [3, 4])
nested[0].append(999)          # 可以!nested变为([1, 2, 999], [3, 4])

# 元组解包( unpacking)
x, y = coords                  # x=10, y=20
first, *rest = (1, 2, 3, 4, 5)  # first=1, rest=[2,3,4,5]
a, b, c = (1, 2, 3, 4)[:3]      # 切片解包

# 性能优势:比列表更省内存,迭代更快

3.3 字典 (dict) - 键值映射

# 创建
person = {
    "name": "Alice",
    "age": 25,
    "skills": ["Python", "SQL"]
}

# 访问与修改
print(person["name"])          # Alice
person["email"] = "alice@example.com"  # 新增键值
person["age"] = 26                    # 修改值

# 安全访问
age = person.get("age", 0)          # 不存在返回默认值
phone = person.get("phone")       # None(不报错)

# 删除
del person["email"]
removed = person.pop("age")       # 删除并返回值

# 遍历
for key in person:               # 仅遍历键
    print(key)

for value in person.values():     # 仅遍历值
    print(value)

for key, value in person.items(): # 遍历键值对
    print(f"{key}: {value}")

# 字典推导式
word_lengths = {word: len(word) for word in ["apple", "banana"]}
# {'apple': 5, 'banana': 6}

# 合并字典
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = {**dict1, **dict2}       # 解包合并,b被覆盖为3
merged = dict1 | dict2            # Python 3.9+ 语法

3.4 集合 (set) - 无序唯一

# 创建
numbers = {1, 2, 3, 3, 3}          # 自动去重为 {1, 2, 3}
empty_set = set()               # 不能用{}(那是空字典)

# 集合运算(高效去重、关系判断)
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

union = a | b                     # 并集: {1,2,3,4,5,6}
intersection = a & b             # 交集: {3,4}
difference = a - b                 # 差集: {1,2}
symmetric_diff = a ^ b           # 对称差: {1,2,5,6}

# 子集判断
a.issubset(b)                     # False
{3, 4}.issubset(a)                 # True

# 添加删除
numbers.add(7)
numbers.discard(100)            # 删除不存在不报错
numbers.remove(100)              # 删除不存在会KeyError

4. 类型转换与检查

4.1 显式转换

# 转字符串
str(123)                  # "123"
repr([1, 2, 3])            # "[1, 2, 3]"(保留Python语法)

# 转数字
int("42")                # 42
float("3.14")             # 3.14
int("3.9")                 # 3(截断小数)

# 转列表/元组
list("abc")               # ['a', 'b', 'c']
list((1, 2, 3))              # [1, 2, 3]
tuple([1, 2, 3])             # (1, 2, 3)

# 转布尔
bool(1)                    # True
bool(0), bool(""), bool([])  # False

4.2 类型检查

type(123)                    # <class 'int'>
isinstance(123, int)       # True(推荐)
isinstance([1,2], (list, tuple))  # True(多类型检查)

# 类型注解(Python 3.5+,非强制,用于提示)
def greet(name: str) -> str:
    return f"Hello, {name}"

from typing import List, Dict, Optional

def process(data: List[Dict[str, int]]) -> Optional[int]:
    # 接收列表(内含字符串键、整数值的字典),返回整数或None
    pass

5. 变量作用域

# LEGB规则:Local -> Enclosing -> Global -> Built-in

global_var = "我在全局"

def outer():
    enclosing_var = "我在嵌套函数外层"

    def inner():
        local_var = "我在局部"
        print(global_var)      # 访问全局
        print(enclosing_var)     # 访问外层

        # 修改全局变量需声明
        global global_var
        global_var = "被修改了"

        # nonlocal修改外层变量(Python 3+)
        nonlocal enclosing_var
        enclosing_var = "也被修改了"

    inner()

outer()

6. 实际应用示例

示例1:数据清洗管道

def clean_data(raw_data: list) -> list:
    """
    清洗原始数据:去重、去空、类型转换
    """
    # 去空
    filtered = [x for x in raw_data if x is not None and str(x).strip() != ""]

    # 去重并保持顺序
    seen = set()
    unique = []
    for item in filtered:
        if item not in seen:
            seen.add(item)
            unique.append(item)

    # 类型转换(字符串转数字)
    return [float(x) if '.' in str(x) else int(x) for x in unique]

# 测试
dirty = ["  123  ", "456", None, "123", "  789.5  ", ""]
cleaned = clean_data(dirty)
print(cleaned)  # [123, 456, 789.5]

示例2:配置管理类

from typing import Dict, Any

class Config:
    _instance = None  # 单例模式

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._settings: Dict[str, Any] = {}
        return cls._instance

    def set(self, key: str, value: Any) -> None:
        self._settings[key] = value

    def get(self, key: str, default=None) -> Any:
        return self._settings.get(key, default)

    def all(self) -> Dict[str, Any]:
        return self._settings.copy()

# 使用
config = Config()
config.set("database", {"host": "localhost", "port": 3306})
db_config = config.get("database")

示例3:类型安全的工厂函数

from typing import Union, List

def create_data_object(data_type: str, value: Union[str, int, List]) -> object:
    """
    根据类型创建不同的数据对象
    """
    factories = {
        "vector": lambda x: list(x) if isinstance(x, (list, tuple)) else [x],
        "scalar": lambda x: x[0] if isinstance(x, (list, tuple)) and len(x) == 1 else x,
        "string": lambda x: str(x)
    }

    if data_type in factories:
        return factories[data_type](value)
    raise ValueError(f"未知类型: {data_type}")

# 测试
print(create_data_object("vector", (1, 2, 3)))      # [1, 2, 3]
print(create_data_object("scalar", [42]))          # 42
print(create_data_object("string", 123))           # "123"

关键原则

  • 需要修改用 list,不需要修改用 tuple
  • 查找用 dict(O(1)),序列用 list/tuple(O(n))
  • 去重用 set
  • 字符串是不可变序列,拼接会产生新对象

 

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐