【Python 】基本数据类型

1.数值类型

# 整数 int x = 10 y = -5 # 浮点数 float a = 3.14 b = 2.0 # 复数 complex c = 3 + 4j # 布尔 bool(是 int 的子类) flag1 = True # 实际上是 1 flag2 = False # 实际上是 0

2.字符串类型

# 字符串 str s1 = "Hello" s2 = 'World' s3 = """多行 字符串""" s4 = f"格式化 {x}"

3.序列类型

# 列表 list(可变) lst = [1, 2, 3, 'a', 'b'] lst.append(4) # 元组 tuple(不可变) tup = (1, 2, 3, 'a') single_tuple = (5,) # 单个元素的元组需要逗号 # 范围 range r = range(5) # 0,1,2,3,4 r2 = range(1, 10, 2) # 1,3,5,7,9

4.集合类型

# 集合 set(无序、不重复) s = {1, 2, 3, 3} # {1, 2, 3} s.add(4) # 冻结集合 frozenset(不可变) fs = frozenset([1, 2, 3])

5.映射类型

# 字典 dict(键值对) d = {'name': 'Alice', 'age': 25} d['city'] = 'Beijing'

6.二进制类型

# 字节 bytes(不可变) b = b'hello' b2 = bytes([65, 66, 67]) # b'ABC' # 字节数组 bytearray(可变) ba = bytearray(b'hello') ba[0] = 72 # 修改第一个字节 # 内存视图 memoryview mv = memoryview(b'hello')

7.None 类型

# 空值 None value = None

类型检查示例

# 使用 type() 函数 print(type(10)) # <class 'int'> print(type(3.14)) # <class 'float'> print(type("hello")) # <class 'str'> print(type([1,2,3])) # <class 'list'> print(type(True)) # <class 'bool'> print(type(None)) # <class 'NoneType'> # 使用 isinstance() 函数 print(isinstance(10, int)) # True print(isinstance(True, bool)) # True print(isinstance(True, int)) # True(bool 是 int 的子类)

运行结果

类型转换

# 显式类型转换 int("10") # 10 float("3.14") # 3.14 str(100) # "100" list((1,2,3)) # [1, 2, 3] tuple([1,2,3]) # (1, 2, 3) set([1,2,2,3]) # {1, 2, 3}

特点总结

  • 可变类型:list、dict、set、bytearray

  • 不可变类型:int、float、str、tuple、frozenset、bytes

  • 有序序列:list、tuple、str、range、bytes

  • 无序集合:set、frozenset、dict(Python 3.7+ 中 dict 保持插入顺序)