Appearance
Python 数据类型详解
本文将介绍 Python 常见的数据类型。
1. 数值类型(Numeric Types)
Python 提供三种主要的数值类型:
1.1 整数(int)
Python 的整数类型 int
,可以表示任意大小的整数。
python
x = 42 # 整数
print(type(x)) # <class 'int'>
1.2 浮点数(float)
浮点数用于表示小数和科学计数法。
python
y = 3.14 # 浮点数
print(type(y)) # <class 'float'>
1.3 复数(complex)
Python 还支持复数,使用 j
表示虚数单位。
python
z = 2 + 3j # 复数
print(type(z)) # <class 'complex'>
2. 布尔类型(Boolean Type)
布尔类型 bool
只有两个值:True
和 False
,用于逻辑运算。
python
is_python_fun = True
print(type(is_python_fun)) # <class 'bool'>
3. 字符串类型(String Type)
字符串 str
用于存储文本,可以使用单引号或双引号定义。
python
s = "Hello, Python!"
print(type(s)) # <class 'str'>
支持多行字符串:
python
multi_line_str = '''
This is a multi-line string.
It spans multiple lines.
'''
字符串支持索引、切片和常见操作:
python
print(s[0]) # H
print(s[0:5]) # Hello
print(len(s)) # 字符串长度
print(s.upper()) # 转换为大写
4. 序列类型(Sequence Types)
Python 具有三种常见的序列类型:列表(list)、元组(tuple)和范围(range)。
4.1 列表(List)
列表是可变的序列,使用 []
表示,可以存储不同类型的元素。
python
my_list = [1, 2, 3, "Python", 3.14]
print(type(my_list)) # <class 'list'>
列表支持索引、切片、修改和方法:
python
my_list.append(42) # 添加元素
print(my_list[0]) # 获取第一个元素
4.2 元组(Tuple)
元组类似于列表,但不可变,使用 ()
定义。
python
my_tuple = (1, 2, 3, "Python")
print(type(my_tuple)) # <class 'tuple'>
元组的元素不能更改,但可以访问:
python
print(my_tuple[1]) # 2
4.3 范围(Range)
range()
用于生成数值序列。
python
r = range(1, 10, 2) # 生成 1,3,5,7,9
print(list(r))
5. 集合类型(Set Types)
集合 set
是无序、不重复的元素集合,使用 {}
创建。
python
my_set = {1, 2, 3, 3, 4}
print(my_set) # {1, 2, 3, 4}
集合的常见操作:
python
my_set.add(5) # 添加元素
my_set.remove(2) # 移除元素
6. 字典类型(Dictionary Type)
字典 dict
是键值对(key-value pair)映射,使用 {}
创建。
python
my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"]) # Alice
字典的常见操作:
python
my_dict["city"] = "New York" # 添加键值对
print(my_dict.keys()) # 获取所有键
print(my_dict.values()) # 获取所有值
7. None 类型
NoneType
只有一个值 None
,表示“无值”或“空值”。
python
x = None
print(type(x)) # <class 'NoneType'>
总结
数据类型 | 说明 | 示例 |
---|---|---|
int | 整数 | 42 |
float | 浮点数 | 3.14 |
complex | 复数 | 2 + 3j |
bool | 布尔值 | True / False |
str | 字符串 | "Hello" |
list | 列表 | [1, 2, 3] |
tuple | 元组 | (1, 2, 3) |
range | 范围 | range(5) |
set | 集合 | {1, 2, 3} |
dict | 字典 | { "key": "value" } |
NoneType | 空值 | None |