Skip to content

数据类型

Python 有丰富的数据类型,包括数字、字符串、布尔值等基本类型,以及列表、元组、字典、集合等复合类型。

数据类型分类

text
┌─────────────────────────────────────────────────────────────────┐
│                     Python 数据类型                              │
├─────────────────────────────────────────────────────────────────┤
│  基本类型:                                                      │
│    - 整数(int)                                                 │
│    - 浮点数(float)                                             │
│    - 复数(complex)                                             │
│    - 布尔值(bool)                                              │
│    - 字符串(str)                                               │
│    - None 类型                                                   │
│                                                                 │
│  复合类型:                                                       │
│    - 列表(list)                                                │
│    - 元组(tuple)                                               │
│    - 字典(dict)                                                │
│    - 集合(set)                                                 │
└─────────────────────────────────────────────────────────────────┘

数字类型

整数(int)

python
# 整数定义
a = 10          # 正整数
b = -20         # 负整数
c = 0           # 零

# 大整数(Python 支持任意大小的整数)
big_number = 123456789012345678901234567890
print(big_number)

# 不同进制
decimal = 10          # 十进制
binary = 0b1010       # 二进制(前缀 0b)
octal = 0o12          # 八进制(前缀 0o)
hexadecimal = 0xA     # 十六进制(前缀 0x)

print(f"十进制:{decimal}")
print(f"二进制:{binary}")
print(f"八进制:{octal}")
print(f"十六进制:{hexadecimal}")

# 进制转换
num = 10
print(f"二进制:{bin(num)}")     # 0b1010
print(f"八进制:{oct(num)}")      # 0o12
print(f"十六进制:{hex(num)}")    # 0xa

浮点数(float)

python
# 浮点数定义
a = 3.14
b = -0.5
c = 2.0

# 科学计数法
d = 1.5e2      # 150.0
e = 2.5e-3     # 0.0025

print(f"科学计数法:{d}, {e}")

# 浮点数精度问题
print(0.1 + 0.2)  # 0.30000000000000004

# 使用 decimal 模块处理精确计算
from decimal import Decimal
result = Decimal('0.1') + Decimal('0.2')
print(result)  # 0.3

# 特殊值
import math
print(f"正无穷:{float('inf')}")
print(f"负无穷:{float('-inf')}")
print(f"非数字:{float('nan')}")

# 判断函数
print(math.isinf(float('inf')))   # True
print(math.isnan(float('nan')))   # True

复数(complex)

python
# 复数定义
c1 = 3 + 4j       # 实部 3,虚部 4
c2 = complex(3, 4)  # 等同于上面

# 访问实部和虚部
print(f"实部:{c1.real}")    # 3.0
print(f"虚部:{c1.imag}")    # 4.0

# 复数运算
c3 = c1 + c2
print(f"复数相加:{c3}")

# 共轭复数
print(f"共轭复数:{c1.conjugate()}")  # (3-4j)

# 模(绝对值)
print(f"模:{abs(c1)}")  # 5.0

布尔类型

python
# 布尔值
is_true = True
is_false = False

# 布尔值是整数的子类
print(True == 1)    # True
print(False == 0)   # True
print(True + True)  # 2

# 布尔转换
print(bool(1))      # True
print(bool(0))      # False
print(bool(""))     # False(空字符串)
print(bool("Hi"))   # True(非空字符串)
print(bool([]))     # False(空列表)
print(bool([1]))    # True(非空列表)

# 以下值转换为 False
# None, False, 0, 0.0, 0j, '', (), [], {}, set(), range(0)
# 其他值转换为 True

字符串类型

python
# 字符串定义
s1 = 'Hello'        # 单引号
s2 = "World"        # 双引号
s3 = '''多行
字符串'''           # 三引号(多行)
s4 = """也是多行
字符串"""

# 转义字符
print("换行:\n制表:\t反斜杠:\\")
print("引号:\"单引号:\'")

# 原始字符串(不转义)
raw_str = r"C:\Users\name\folder"
print(raw_str)

# 字符串操作
text = "Hello, Python!"
print(f"长度:{len(text)}")
print(f"第一个字符:{text[0]}")
print(f"最后一个字符:{text[-1]}")
print(f"切片:{text[0:5]}")
print(f"重复:{'Hi' * 3}")

# 字符串方法
print(text.lower())       # 小写
print(text.upper())       # 大写
print(text.replace("Python", "World"))
print(text.split(", "))   # 分割
print("-".join(["a", "b", "c"]))  # 连接

None 类型

python
# None 表示"无"或"空"
result = None
print(result)        # None
print(type(result))  # <class 'NoneType'>

# None 与其他值的区别
print(None == False)   # False
print(None == 0)       # False
print(None == "")      # False
print(None == [])      # False

# 判断是否为 None(使用 is)
x = None
if x is None:
    print("x 是 None")

# 函数默认返回 None
def no_return():
    pass

result = no_return()
print(result)  # None

类型转换

显式转换

python
# 转换为整数
print(int(3.14))        # 3(截断)
print(int("123"))       # 123
print(int("1010", 2))   # 10(二进制转十进制)
# print(int("3.14"))    # 报错

# 转换为浮点数
print(float(10))        # 10.0
print(float("3.14"))    # 3.14
print(float("1e2"))     # 100.0

# 转换为字符串
print(str(123))         # "123"
print(str(3.14))        # "3.14"
print(str(True))        # "True"

# 转换为布尔值
print(bool(1))          # True
print(bool(0))          # False
print(bool(""))         # False
print(bool("Hello"))    # True

# 转换为列表
print(list("Hello"))    # ['H', 'e', 'l', 'l', 'o']
print(list((1, 2, 3)))  # [1, 2, 3]

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

# 转换为集合
print(set([1, 2, 2, 3]))  # {1, 2, 3}

隐式转换

python
# 数字运算中的隐式转换
a = 10        # int
b = 3.14      # float
result = a + b
print(type(result))  # <class 'float'>

# 布尔值参与运算
result = True + 5  # True 被当作 1
print(result)       # 6

# 字符串拼接
result = "年龄:" + str(25)
print(result)

类型检查

type() 函数

python
# 获取类型
print(type(10))         # <class 'int'>
print(type(3.14))       # <class 'float'>
print(type("Hello"))    # <class 'str'>
print(type(True))       # <class 'bool'>
print(type([1, 2]))     # <class 'list'>
print(type({"a": 1}))   # <class 'dict'>

# 比较类型
x = 10
if type(x) == int:
    print("x 是整数")

# 获取类型名称
print(type(10).__name__)  # int

isinstance() 函数

python
# isinstance() 检查类型(推荐)
print(isinstance(10, int))        # True
print(isinstance(3.14, float))    # True
print(isinstance("Hi", str))      # True

# 检查多个类型
print(isinstance(10, (int, float)))  # True
print(isinstance(3.14, (int, float)))  # True

# isinstance 考虑继承关系
print(isinstance(True, int))       # True(bool 是 int 的子类)

# type() vs isinstance()
print(type(True) == int)           # False
print(isinstance(True, int))       # True

可变与不可变类型

python
# 不可变类型:值不能被修改
# int, float, str, tuple

# 整数不可变
x = 10
x = 20  # 创建新对象,不是修改原对象

# 字符串不可变
s = "Hello"
# s[0] = 'h'  # 报错
s = "hello"  # 创建新字符串

# 可变类型:值可以被修改
# list, dict, set

# 列表可变
lst = [1, 2, 3]
lst[0] = 10  # 修改原列表
print(lst)  # [10, 2, 3]

# 字典可变
d = {"a": 1}
d["b"] = 2  # 添加新键值对
print(d)  # {'a': 1, 'b': 2}

# 可变类型的注意事项
lst1 = [1, 2, 3]
lst2 = lst1  # 引用同一个对象
lst2.append(4)
print(lst1)  # [1, 2, 3, 4](lst1 也被修改了)

# 使用 copy() 创建副本
lst3 = lst1.copy()
lst3.append(5)
print(lst1)  # [1, 2, 3, 4](不受影响)
print(lst3)  # [1, 2, 3, 4, 5]

小结

本章我们学习了:

  • 数字类型:整数、浮点数、复数
  • 布尔类型:True 和 False
  • 字符串类型:字符串的定义和基本操作
  • None 类型:表示"无"
  • 类型转换:显式转换和隐式转换
  • 类型检查:type() 和 isinstance()
  • 可变与不可变:理解类型的可变性

下一章,我们将学习 运算符,了解 Python 中的各种运算操作。