Python 的数据类型

Python 的数据类型(Data Types)是指变量可以存储的数据种类。比如数字、文字、真假判断、列表等。

Python 是动态类型语言,不需要提前声明变量的类型,Python 会根据赋值自动识别。

复制代码
name = "Alice"       # 字符串age = 25             # 整数height = 1.75        # 浮点数is_student = True    # 布尔值

一、Python 常见的数据类型

Python 内置数据类型可以分为以下几大类。

  1. 数值类型(Numeric)

int / float / complex

  • int:整数,如 10、-5

  • float:浮点数,如 3.14、-0.5

  • complex:复数,如 2 + 3j

    a = 10b = 3.14c = 2 + 3j

  1. 字符串类型(String)

str

用于存储文本,需要用引号包裹。

复制代码
name = "Alice"message = 'Hello Python'

字符串可以包含中文、英文、数字和符号。

  1. 列表类型(List)

list

有序、可修改,可以存储多个元素,允许重复。

复制代码
fruits = ["apple", "banana", "apple"]fruits.append("orange")

适合存储一组需要增删改的数据。

  1. 元组类型(Tuple)

tuple

有序,但创建后不能修改元素。

复制代码
point = (10, 20)

适合表示固定的一组数据,例如坐标。

  1. 字典类型(Dictionary)

dict

通过键(key)和值(value)存储数据。

复制代码
user = {    "name": "Alice",    "age": 25}print(user["name"])  # Alice

常用于存储用户信息、API 返回的数据、配置参数等。

  1. 集合类型(Set)

set / frozenset

不保存重复元素,适合去重和集合运算。

复制代码
numbers = {1, 2, 2, 3}print(numbers)  # {1, 2, 3}

set 可修改,frozenset 不可修改。

  1. 布尔类型(Boolean)

bool

只有两个值:True 和 False。

复制代码
is_login = Trueprint(10 > 5)  # True

常用于 if 条件判断和循环控制。

  1. 空值类型(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。

相关推荐
FITA阿泽要努力1 小时前
Sub Agent:上下文管理的艺术
人工智能·python·agent
全栈弄潮儿1 小时前
Python实战第10期:异常处理
后端·python·编程语言
yuniko-n1 小时前
【JUC】JMM(Java 内存模型)
java·开发语言
十碗饭吃不饱1 小时前
MySQL InnoDB RR 隔离下二级索引临键锁引发 INSERT 锁超时 全链路解析
java·数据库·mysql
余槐i1 小时前
加了Cookie yt-dlp仍报HTTP 403:3个容易漏的请求头差异
python·http·ffmpeg·开发工具·yt-dlp
专业程序开发源1 小时前
springboot校企合作双选会一站式预约与面试系统16010-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·面试·php·课程设计
菜鸟不秃头1 小时前
手搓 ViT -- 并完成图像分类任务
python