Python 的数据类型(Data Types)是指变量可以存储的数据种类。比如数字、文字、真假判断、列表等。
Python 是动态类型语言,不需要提前声明变量的类型,Python 会根据赋值自动识别。
name = "Alice" # 字符串age = 25 # 整数height = 1.75 # 浮点数is_student = True # 布尔值
一、Python 常见的数据类型
Python 内置数据类型可以分为以下几大类。
- 数值类型(Numeric)
int / float / complex
-
int:整数,如10、-5 -
float:浮点数,如3.14、-0.5 -
complex:复数,如2 + 3ja = 10b = 3.14c = 2 + 3j
- 字符串类型(String)
str
用于存储文本,需要用引号包裹。
name = "Alice"message = 'Hello Python'
字符串可以包含中文、英文、数字和符号。
- 列表类型(List)
list
有序、可修改,可以存储多个元素,允许重复。
fruits = ["apple", "banana", "apple"]fruits.append("orange")
适合存储一组需要增删改的数据。
- 元组类型(Tuple)
tuple
有序,但创建后不能修改元素。
point = (10, 20)
适合表示固定的一组数据,例如坐标。
- 字典类型(Dictionary)
dict
通过键(key)和值(value)存储数据。
user = { "name": "Alice", "age": 25}print(user["name"]) # Alice
常用于存储用户信息、API 返回的数据、配置参数等。
- 集合类型(Set)
set / frozenset
不保存重复元素,适合去重和集合运算。
numbers = {1, 2, 2, 3}print(numbers) # {1, 2, 3}
set 可修改,frozenset 不可修改。
- 布尔类型(Boolean)
bool
只有两个值:True 和 False。
is_login = Trueprint(10 > 5) # True
常用于 if 条件判断和循环控制。
- 空值类型(None)
NoneType
None 表示当前没有值,或者没有有效结果。
result = Noneprint(result) # None
常用于表示函数没有返回结果,或初始化一个尚未赋值的状态。
二、哪些数据类型可以修改?
这是学习 Python 时非常重要的知识点。
| 数据类型 | 是否可变 | 示例 |
|---|---|---|
int |
不可变 | 10 |
float |
不可变 | 3.14 |
bool |
不可变 | True |
str |
不可变 | "hello" |
tuple |
不可变 | (1, 2) |
frozenset |
不可变 | frozenset({1, 2}) |
list |
可变 | [1, 2] |
dict |
可变 | {"a": 1} |
set |
可变 | {1, 2} |
例如,列表可以直接修改:
numbers = [1, 2, 3]numbers[0] = 100print(numbers) # [100, 2, 3]
但字符串不能直接修改其中的字符:
text = "hello"# text[0] = "H" # TypeError
三、如何查看数据类型?
使用 Python 内置函数 type()。
print(type(100)) # <class 'int'>print(type(3.14)) # <class 'float'>print(type("hello")) # <class 'str'>print(type([1, 2, 3])) # <class 'list'>print(type((1, 2))) # <class 'tuple'>print(type({"a": 1})) # <class 'dict'>print(type({1, 2, 3})) # <class 'set'>print(type(True)) # <class 'bool'>print(type(None)) # <class 'NoneType'>
如果想判断一个变量是不是字符串,可以使用 isinstance():
name = "Alice"print(isinstance(name, str)) # Trueprint(isinstance(name, int)) # False
四、数据类型之间如何转换?
Python 提供了常见的类型转换函数。
| 函数 | 作用 | 示例 |
|---|---|---|
int() |
转为整数 | int("123") → 123 |
float() |
转为浮点数 | float("3.14") → 3.14 |
str() |
转为字符串 | str(123) → "123" |
bool() |
转为布尔值 | bool(1) → True |
list() |
转为列表 | list("abc") → ['a', 'b', 'c'] |
tuple() |
转为元组 | tuple([1, 2]) → (1, 2) |
set() |
转为集合 | set([1, 1, 2]) → {1, 2} |
dict() |
构建字典 | dict([("a", 1)]) → {'a': 1} |
注意:并非所有转换都有效。例如 int("hello") 会报 ValueError。