上一篇
Python3 基本数据类型教程 - 全面指南
- 综合资讯
- 2025-07-15
- 1188
Python3 基本数据类型教程
数据类型的重要性
在Python编程中,数据类型是构建程序的基础。理解不同数据类型及其特性是编写高效、可维护代码的关键。Python是一种动态类型语言,这意味着你不需要显式声明变量的类型,解释器会在运行时自动推断。
Python3中的基本数据类型可分为以下几类:数字类型、序列类型、映射类型和集合类型。本教程将详细介绍每种类型及其常见操作。
1. 数字类型 (Numeric Types)
整数 (int)
整数是不带小数点的数字,可以是正数或负数。
# 整数示例
age = 25
temperature = -10
population = 7800000000
# 整数运算
print(10 + 5) # 输出: 15
print(20 - 8) # 输出: 12
print(6 * 7) # 输出: 42
print(15 / 4) # 输出: 3.75 (注意结果是浮点数)
print(15 // 4) # 输出: 3 (整除)
print(15 % 4) # 输出: 3 (取余)
print(2 ** 8) # 输出: 256 (幂运算)
浮点数 (float)
浮点数表示带有小数点的数字,用于更精确的数值计算。
# 浮点数示例
pi = 3.14159
temperature = 36.6
price = 9.99
# 浮点数运算
print(0.1 + 0.2) # 输出: 0.30000000000000004 (浮点数精度问题)
print(round(0.1 + 0.2, 1)) # 输出: 0.3 (使用round函数控制精度)
print(10.5 * 2) # 输出: 21.0
print(10.0 // 3) # 输出: 3.0 (浮点数整除)
布尔值 (bool)
布尔值表示真(True)或假(False),常用于条件判断。
# 布尔值示例
is_active = True
has_permission = False
# 布尔运算
print(True and False) # 输出: False
print(True or False) # 输出: True
print(not True) # 输出: False
# 布尔值在条件判断中的应用
if age >= 18:
print("成年人")
else:
print("未成年人")
2. 字符串 (str)
字符串是由字符组成的序列,用于表示文本信息。在Python中,字符串是不可变的。
# 字符串创建
name = "Alice"
message = 'Hello, World!'
multiline = """这是一个
多行字符串"""
# 字符串操作
print(len(name)) # 输出: 5 (字符串长度)
print(name + " Smith") # 输出: Alice Smith (字符串拼接)
print("Hello, " * 3) # 输出: Hello, Hello, Hello,
print("a" in "apple") # 输出: True (成员检查)
# 字符串索引和切片
s = "Python"
print(s[0]) # 输出: P (索引从0开始)
print(s[-1]) # 输出: n (负索引表示从末尾开始)
print(s[2:5]) # 输出: tho (切片操作)
print(s[:4]) # 输出: Pyth
print(s[2:]) # 输出: thon
print(s[::-1]) # 输出: nohtyP (反转字符串)
# 字符串常用方法
print("hello".upper()) # 输出: HELLO
print("WORLD".lower()) # 输出: world
print(" python ".strip()) # 输出: python (移除两端空白)
print("apple,banana,orange".split(",")) # 输出: ['apple', 'banana', 'orange']
print("hello world".replace("world", "Python")) # 输出: hello Python
print("Python".startswith("Py")) # 输出: True
print("Python".endswith("on")) # 输出: True
3. 列表 (list)
列表是有序的可变序列,可以包含不同类型的元素。列表使用方括号[]表示。
# 列表创建
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [10, "hello", 3.14, True]
# 列表操作
print(len(numbers)) # 输出: 5 (列表长度)
print(fruits[1]) # 输出: banana (索引访问)
fruits[0] = "orange" # 修改元素
print(fruits) # 输出: ['orange', 'banana', 'cherry']
# 列表切片
print(numbers[1:4]) # 输出: [2, 3, 4]
print(numbers[::2]) # 输出: [1, 3, 5] (步长为2)
# 列表方法
fruits.append("grape") # 添加元素到末尾
print(fruits) # 输出: ['orange', 'banana', 'cherry', 'grape']
fruits.insert(1, "mango") # 在指定位置插入元素
print(fruits) # 输出: ['orange', 'mango', 'banana', 'cherry', 'grape']
fruits.remove("banana") # 移除指定元素
print(fruits) # 输出: ['orange', 'mango', 'cherry', 'grape']
popped = fruits.pop() # 移除并返回最后一个元素
print(popped) # 输出: grape
print(fruits) # 输出: ['orange', 'mango', 'cherry']
numbers.sort() # 排序(原地修改)
print(numbers) # 输出: [1, 2, 3, 4, 5]
# 列表推导式
squares = [x**2 for x in range(1, 6)]
print(squares) # 输出: [1, 4, 9, 16, 25]
4. 元组 (tuple)
元组是有序的不可变序列,使用圆括号()表示。与列表不同,元组创建后不能修改。
# 元组创建
coordinates = (10, 20)
colors = ("red", "green", "blue")
single_element = (42,) # 注意: 单个元素的元组需要加逗号
# 元组操作
print(coordinates[0]) # 输出: 10 (索引访问)
print(len(colors)) # 输出: 3 (长度)
print("green" in colors) # 输出: True (成员检查)
# 元组解包
x, y = coordinates
print(f"x={x}, y={y}") # 输出: x=10, y=20
# 元组与列表的转换
numbers_list = [1, 2, 3]
numbers_tuple = tuple(numbers_list)
print(numbers_tuple) # 输出: (1, 2, 3)
# 元组的不可变性
# 下面的操作会引发错误
# coordinates[0] = 15 # TypeError: 'tuple' object does not support item assignment
5. 字典 (dict)
字典是无序的键值对集合,使用花括号{}表示。字典中的键必须是不可变类型,如字符串、数字或元组。
# 字典创建
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
scores = dict(math=95, english=88, science=92)
# 字典操作
print(person["name"]) # 输出: Alice (按键访问)
person["age"] = 31 # 修改值
person["email"] = "alice@example.com" # 添加新键值对
# 字典方法
print(person.keys()) # 输出: dict_keys(['name', 'age', 'city', 'email'])
print(person.values()) # 输出: dict_values(['Alice', 31, 'New York', 'alice@example.com'])
print(person.get("country", "USA")) # 输出: USA (安全获取,键不存在时返回默认值)
# 遍历字典
for key, value in person.items():
print(f"{key}: {value}")
# 字典推导式
squares = {x: x*x for x in range(1, 6)}
print(squares) # 输出: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
6. 集合 (set)
集合是无序且不重复元素的集合,使用花括号{}或set()函数创建。
# 集合创建
fruits = {"apple", "banana", "cherry"}
numbers = set([1, 2, 3, 4, 5])
# 集合操作
fruits.add("orange") # 添加元素
fruits.add("apple") # 添加重复元素无效
print(fruits) # 输出: {'apple', 'banana', 'cherry', 'orange'}
fruits.remove("banana") # 移除元素
print(fruits) # 输出: {'apple', 'cherry', 'orange'}
# 集合运算
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
print(set_a | set_b) # 并集: {1, 2, 3, 4, 5, 6}
print(set_a & set_b) # 交集: {3, 4}
print(set_a - set_b) # 差集: {1, 2}
print(set_a ^ set_b) # 对称差集: {1, 2, 5, 6}
# 集合推导式
even_squares = {x**2 for x in range(10) if x**2 % 2 == 0}
print(even_squares) # 输出: {0, 4, 16, 36, 64}
总结
掌握Python的基本数据类型是编程的基础。以下是关键点总结:
- 数字类型:int(整数)、float(浮点数)、bool(布尔值)
- 序列类型:str(字符串,不可变)、list(列表,可变)、tuple(元组,不可变)
- 映射类型:dict(字典,键值对集合)
- 集合类型:set(无序不重复元素集)
理解每种数据类型的特性和适用场景,能帮助你编写更高效、更易读的Python代码。在实际编程中,选择合适的数据类型往往能简化操作并提高性能。
本文由JingLv于2025-07-15发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://pjw.521pj.cn/20255644.html
发表评论