Appearance
章节2 数据类型与流程控制
授课时长:约4-5学时
适用对象:已掌握Python环境搭建的学员
教学方式:讲授 + 代码演示 + 随堂练习
一、学习目标
| 目标分类 | 具体目标 |
|---|---|
| 知识目标 | 理解六大基础数据类型及其可变性、容器操作与字符串处理、条件循环逻辑 |
| 技能目标 | 熟练运用推导式简化代码、掌握内置函数与f-string格式化 |
| 素养目标 | 培养数据类型意识,写出简洁高效的Python代码 |
二、核心知识点
1️⃣ 变量常量与六大基础数据类型
1.1 变量与常量
变量:在内存中存储数据的命名容器,Python中变量无需显式声明类型。
python
# 变量命名规则:
# 1. 只能包含字母、数字、下划线
# 2. 不能以数字开头
# 3. 区分大小写
# 4. 不能是Python关键字
name = "Alice" # str
age = 25 # int
height = 1.75 # float
is_student = True # bool
# 多重赋值
a = b = c = 0
x, y, z = 1, 2, 3
# 交换两个变量(Python特色)
a, b = b, a常量:Python没有真正的常量,约定使用全大写表示不应修改的值。
python
# 约定:全大写表示常量
PI = 3.14159
MAX_RETRIES = 5
DEFAULT_ENCODING = "utf-8"1.2 六大基础数据类型总览
python
"""
┌──────────────────────────────────────────────┐
│ Python 六大基础数据类型 │
├─────────────┬──────────┬──────────────────────┤
│ 类型 │ 关键字 │ 示例 │
├─────────────┼──────────┼──────────────────────┤
│ 整型 │ int │ 42, -3, 0x1A │
│ 浮点型 │ float │ 3.14, -0.5, 1e-3 │
│ 字符串 │ str │ "Hello", 'Python' │
│ 布尔型 │ bool │ True, False │
│ 空值 │ NoneType│ None │
│ 字节串 │ bytes │ b"data", b'\x00' │
└─────────────┴──────────┴──────────────────────┘
"""
# 使用 type() 查看类型
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>
print(type(b"data")) # <class 'bytes'>
# 类型转换
print(int(3.14)) # 3
print(float("3.14")) # 3.14
print(str(42)) # "42"
print(bool(1)) # True
print(bool(0)) # False
print(bool("")) # False
print(bool("abc")) # True1.3 各类型深入讲解
int 整型
python
# Python 3 中 int 是任意精度(不会溢出)
big_number = 10 ** 100
print(big_number) # 1000000000000000000000000000...
# 不同进制表示
decimal = 255 # 十进制
binary = 0b11111111 # 二进制 → 255
octal = 0o377 # 八进制 → 255
hexadecimal = 0xFF # 十六进制 → 255
# 进制转换
print(bin(255)) # '0b11111111'
print(oct(255)) # '0o377'
print(hex(255)) # '0xff'
print(int("FF", 16)) # 255float 浮点型
python
# 浮点数精度问题(IEEE 754标准)
print(0.1 + 0.2) # 0.30000000000000004 ❌
print(round(0.1 + 0.2, 2)) # 0.3 ✅
# 科学计数法
print(1e3) # 1000.0
print(1e-3) # 0.001
# 特殊值
import math
print(float('inf')) # 无穷大
print(float('-inf')) # 负无穷大
print(float('nan')) # NaN (Not a Number)
print(math.isnan(float('nan'))) # Truestr 字符串
python
# 三种引号
s1 = "双引号"
s2 = '单引号'
s3 = """三引号
支持换行
哦"""
# 转义字符
print("Hello\nWorld") # 换行
print("Tab\there") # 制表符
print("她说:\"你好\"") # 转义引号
# 原始字符串(路径常用)
path = r"C:\Users\name\docs"
print(path) # C:\Users\name\docsbool 布尔型
python
# 布尔值实际上是 int 的子类
print(True == 1) # True
print(False == 0) # True
print(True + True) # 2
# 布尔上下文中的"假值"
# False, 0, 0.0, "", [], (), {}, None, set()
if not []:
print("空列表是假值")
# 布尔上下文中的"真值"
# 非零数字、非空字符串、非空容器...
if [1, 2]:
print("非空列表是真值")None 空值
python
# None 表示"没有值"或"空"
result = None
print(result is None) # True ✅(用 is 比较)
print(result == None) # True ✅(但不推荐)
# 常见使用场景
def find_user(id):
if id == 0:
return None # 表示未找到
return {"name": "Alice"}
user = find_user(0)
if user is None:
print("用户不存在")bytes 字节串
python
# 字节串是二进制数据,不可变序列
data = b"hello"
print(data[0]) # 104 (h的ASCII码)
print(type(data)) # <class 'bytes'>
# 字符串 ↔ 字节串 转换
text = "你好"
encoded = text.encode("utf-8") # str → bytes
print(encoded) # b'\xe4\xbd\xa0\xe5\xa5\xbd'
decoded = encoded.decode("utf-8") # bytes → str
print(decoded) # 你好2️⃣ 列表字典元组集合容器操作
2.1 容器类型总览
| 类型 | 关键字 | 可变 | 有序 | 元素唯一 | 示例 |
|---|---|---|---|---|---|
| 列表 | list | ✅ | ✅ | ❌ | [1, 2, 3] |
| 字典 | dict | ✅ | ✅(3.7+) | Key唯一 | {"a": 1} |
| 元组 | tuple | ❌ | ✅ | ❌ | (1, 2, 3) |
| 集合 | set | ✅ | ❌ | ✅ | {1, 2, 3} |
2.2 列表(list)
python
# 创建
nums = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
empty = []
list_from_range = list(range(1, 6)) # [1, 2, 3, 4, 5]
# 索引与切片
nums = [10, 20, 30, 40, 50]
print(nums[0]) # 10 (正向索引)
print(nums[-1]) # 50 (反向索引)
print(nums[1:3]) # [20, 30] (切片:含头不含尾)
print(nums[:3]) # [10, 20, 30]
print(nums[::2]) # [10, 30, 50] (步长)
print(nums[::-1]) # [50, 40, 30, 20, 10] (反转)
# 常用方法
nums = [1, 2, 3]
nums.append(4) # [1, 2, 3, 4] 末尾追加
nums.insert(0, 0) # [0, 1, 2, 3, 4] 指定位置插入
nums.extend([5, 6]) # [0,1,2,3,4,5,6] 扩展列表
nums.remove(3) # 删除第一个匹配元素
popped = nums.pop() # 弹出末尾元素 → 6
nums.pop(0) # 弹出索引0元素 → 0
nums.sort() # 升序排序(原地)
nums.sort(reverse=True) # 降序
nums.reverse() # 反转
index = nums.index(2) # 查找元素索引
count = nums.count(2) # 统计出现次数
nums.clear() # 清空列表
# 列表的复制(⚠️ 浅拷贝 vs 深拷贝)
original = [[1, 2], [3, 4]]
shallow = original.copy() # 浅拷贝:内层列表仍是引用
import copy
deep = copy.deepcopy(original) # 深拷贝:完全独立2.3 元组(tuple)
python
# 不可变列表
point = (3, 5)
single = (1,) # ⚠️ 单元素元组必须加逗号
empty = tuple()
rgb = tuple([255, 0, 0]) # 从列表转换
# 元组解包(非常实用)
x, y = (10, 20)
a, b, *rest = (1, 2, 3, 4, 5)
print(a) # 1
print(b) # 2
print(rest) # [3, 4, 5]
# 元组不可变性
# t = (1, 2, 3)
# t[0] = 100 # ❌ TypeError: 'tuple' object does not support item assignment
# 命名元组(namedtuple)
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 5)
print(p.x, p.y) # 3 5 ✅ 兼具元组的轻量和字典的可读性2.4 字典(dict)
python
# 创建
student = {
"name": "张三",
"age": 20,
"scores": {"math": 95, "english": 88}
}
empty = {}
from_pairs = dict([("a", 1), ("b", 2)])
# 访问(注意安全访问方式)
name = student["name"] # ✅ 存在时直接访问
# phone = student["phone"] # ❌ KeyError
phone = student.get("phone") # ✅ 不存在返回 None
phone = student.get("phone", "未知") # ✅ 返回默认值
# 增删改
student["grade"] = "大一" # 新增
student["age"] = 21 # 修改
del student["grade"] # 删除
popped = student.pop("age") # 弹出并删除
# 遍历
for key in student: # 遍历键
print(key)
for value in student.values(): # 遍历值
print(value)
for key, value in student.items(): # 遍历键值对(推荐)
print(f"{key}: {value}")
# 字典合并(Python 3.9+)
d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "b": 4}
merged = d1 | d2 # {"a": 1, "b": 4, "c": 3}
d1 |= d2 # 原地合并(d1被修改)
# 默认值字典
from collections import defaultdict
word_count = defaultdict(int)
for char in "hello world":
word_count[char] += 1
print(dict(word_count))2.5 集合(set)
python
# 创建
fruits = {"apple", "banana", "orange"}
empty = set() # ❌ 不是 {}({}是空字典)
from_list = set([1, 2, 2, 3]) # {1, 2, 3} 自动去重
# 集合运算(非常强大)
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # 并集 {1,2,3,4,5,6}
print(a & b) # 交集 {3,4}
print(a - b) # 差集 {1,2}
print(a ^ b) # 对称差 {1,2,5,6}
# 集合判断
print({1, 2}.issubset({1, 2, 3})) # True (子集)
print({1, 2, 3}.issuperset({1, 2})) # True (超集)
print({1, 2}.isdisjoint({3, 4})) # True (无交集)
# 去重是最常见的用途
names = ["Alice", "Bob", "Alice", "Charlie", "Bob"]
unique_names = list(set(names))
print(unique_names) # ['Alice', 'Bob', 'Charlie']3️⃣ 字符串高级处理与格式化
3.1 字符串常用方法
python
text = " Hello, Python World! "
# 大小写转换
print(text.upper()) # ' HELLO, PYTHON WORLD! '
print(text.lower()) # ' hello, python world! '
print(text.title()) # ' Hello, Python World! '
print(text.capitalize()) # ' hello, python world! '
print(text.swapcase()) # 大小写互换
# 查找与替换
print(text.strip()) # 'Hello, Python World!'(去首尾空白)
print(text.find("Python")) # 9 (找到返回索引)
print(text.find("Java")) # -1 (未找到)
print(text.index("Python")) # 9 (找到返回索引)
# print(text.index("Java")) # ❌ ValueError
print(text.replace("Python", "Java")) # 替换
print(text.count("o")) # 3 (统计出现次数)
print(text.startswith(" ")) # True
print(text.endswith("! ")) # True
# 分割与连接
words = "apple,banana,orange"
print(words.split(",")) # ['apple', 'banana', 'orange']
lines = "line1\nline2\nline3"
print(lines.splitlines()) # ['line1', 'line2', 'line3']
parts = ["2024", "03", "15"]
print("-".join(parts)) # '2024-03-15' ✅ 常用
# 字符判断
print("abc123".isalnum()) # True (字母数字)
print("abc".isalpha()) # True (纯字母)
print("123".isdigit()) # True (纯数字)
print(" ".isspace()) # True (空白字符)
print("Hello".istitle()) # True (标题格式)3.2 F-string 格式化(Python 3.6+)
python
# 基本用法
name = "Alice"
age = 25
print(f"我叫{name},今年{age}岁。")
# 表达式计算
print(f"2 + 3 = {2+3}")
print(f"圆的面积(r=5):{3.14159 * 5 ** 2:.2f}")
# 格式说明符
price = 19.99
print(f"价格: {price:.2f}元") # 19.99元(两位小数)
print(f"价格: {price:>10.2f}元") # " 19.99元"(右对齐)
print(f"价格: {price:<10.2f}元") # 左对齐
print(f"价格: {price:^10.2f}元") # 居中对齐
# 数字格式化
num = 1234567.89
print(f"{num:,.2f}") # 1,234,567.89(千分位)
print(f"{num:.2e}") # 1.23e+06(科学计数法)
print(f"{42:b}") # 101010(二进制)
print(f"{255:x}") # ff(十六进制)
# 对齐与填充
print(f"|{'hello':*>20}|") # |***************hello|
print(f"|{'hello':*^20}|") # |*******hello********|
print(f"|{'hello':*<20}|") # |hello***************|
# 日期格式化
from datetime import datetime
now = datetime.now()
print(f"{now:%Y-%m-%d %H:%M:%S}") # 2024-03-15 14:30:00
print(f"{now:%Y年%m月%d日}") # 2024年03月15日
# 多行f-string
name, age, city = "Alice", 25, "北京"
info = (
f"姓名: {name}\n"
f"年龄: {age}\n"
f"城市: {city}"
)
print(info)3.3 三种格式化对比
python
name, score = "Bob", 92.5
# 方式1:%-formatting(旧式)
print("姓名: %s, 分数: %.1f" % (name, score))
# 方式2:str.format()
print("姓名: {}, 分数: {:.1f}".format(name, score))
# 方式3:f-string(推荐 ✅)
print(f"姓名: {name}, 分数: {score:.1f}")4️⃣ 条件判断与循环结构
4.1 条件判断
python
# if-elif-else 结构
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"分数: {score}, 等级: {grade}")
# 条件表达式(三元运算符)
age = 18
status = "成年" if age >= 18 else "未成年"
print(status)
# 逻辑运算符:and / or / not
user_age = 17
has_permission = True
if user_age >= 18 and has_permission:
print("允许访问")
elif user_age >= 18 or has_permission:
print("部分权限")
else:
print("拒绝访问")
# 链式比较(Python特色)
x = 50
print(10 < x < 100) # True ✅
print(10 < x < 30) # False
print(0 < x <= 50) # True4.2 while 循环
python
# 基本语法
count = 0
while count < 5:
print(f"第{count + 1}次循环")
count += 1
# break 与 continue
i = 0
while True:
i += 1
if i == 3:
continue # 跳过本次循环
if i > 5:
break # 终止循环
print(i)
# while-else(很少用,但了解)
n = 0
while n < 3:
print(n)
n += 1
else:
print("循环正常结束(未被break打断)")4.3 for 循环
python
# 遍历可迭代对象
fruits = ["苹果", "香蕉", "橘子"]
for fruit in fruits:
print(fruit)
# range()
for i in range(5): # 0,1,2,3,4
print(i)
for i in range(2, 10, 2): # 2,4,6,8
print(i)
# enumerate() — 同时获取索引和值
names = ["Alice", "Bob", "Charlie"]
for index, name in enumerate(names, start=1):
print(f"第{index}名: {name}")
# zip() — 并行遍历
subjects = ["语文", "数学", "英语"]
scores = [92, 88, 95]
for subject, score in zip(subjects, scores):
print(f"{subject}: {score}分")
# reversed() — 反向遍历
for char in reversed("Python"):
print(char)
# sorted() — 排序遍历
nums = [3, 1, 4, 1, 5, 9]
for n in sorted(nums):
print(n)4.4 循环控制模式
python
# 模式1:计数器模式
total = 0
for num in range(1, 101):
total += num
print(f"1+2+...+100 = {total}")
# 模式2:标志位模式
found = False
nums = [3, 7, 2, 9, 4]
target = 9
for num in nums:
if num == target:
found = True
break
print(f"找到{target}: {found}")
# 模式3:累加器模式
text = "hello"
vowels = "aeiou"
count = 0
for char in text:
if char in vowels:
count += 1
print(f"元音字母个数: {count}")5️⃣ 推导式与内置函数
5.1 列表推导式
python
# 基本语法:[表达式 for 变量 in 可迭代对象 if 条件]
# 基础
squares = [x ** 2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 带条件
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# 嵌套循环
pairs = [(x, y) for x in [1, 2, 3] for y in ['a', 'b']]
print(pairs) # [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]
# 三目运算结合
labels = ["偶数" if x % 2 == 0 else "奇数" for x in range(10)]
# 字符串处理
words = ["hello", "world", "python", "AI"]
upper_words = [word.upper() for word in words if len(word) > 4]
print(upper_words) # ['HELLO', 'WORLD', 'PYTHON']5.2 字典推导式
python
# 基本语法:{key_expr: value_expr for 变量 in 可迭代对象 if 条件}
# 生成平方字典
square_dict = {x: x ** 2 for x in range(1, 6)}
print(square_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 反转键值
original = {"a": 1, "b": 2, "c": 3}
reversed_dict = {v: k for k, v in original.items()}
print(reversed_dict) # {1: 'a', 2: 'b', 3: 'c'}
# 过滤
scores = {"张三": 85, "李四": 92, "王五": 78, "赵六": 95}
passed = {name: score for name, score in scores.items() if score >= 80}5.3 集合推导式
python
# 基本语法:{表达式 for 变量 in 可迭代对象 if 条件}
nums = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique_squares = {x ** 2 for x in nums}
print(unique_squares) # {1, 4, 9, 16}5.4 生成器推导式
python
# 使用圆括号得到的是生成器对象(惰性求值)
gen = (x ** 2 for x in range(1000000))
print(gen) # <generator object <genexpr> at 0x...>
print(next(gen)) # 0
print(next(gen)) # 1
print(next(gen)) # 4
# 需要时转为列表(不推荐全量转换大生成器)
small_list = list(x ** 2 for x in range(10))5.5 常用内置函数
python
# ──────────────────────────────────────────
# 数学运算
abs(-5) # 5
sum([1, 2, 3]) # 6
max(3, 7, 2) # 7
min(3, 7, 2) # 2
pow(2, 3) # 8
round(3.14159, 2) # 3.14
divmod(10, 3) # (3, 1) 商和余数
# ──────────────────────────────────────────
# 类型检查
isinstance(42, int) # True
issubclass(bool, int) # True
callable(print) # True
# ──────────────────────────────────────────
# 迭代工具
all([True, True, False]) # False(全真才真)
any([True, False, False]) # True(有真即真)
len([1, 2, 3]) # 3
sorted([3, 1, 2], reverse=True) # [3, 2, 1]
reversed([1, 2, 3]) # 反向迭代器
# ──────────────────────────────────────────
# 其他实用函数
id("hello") # 对象的内存地址
hash("hello") # 哈希值
help(print) # 帮助文档
dir(list) # 对象的所有属性和方法
repr(42) # '42'(官方字符串表示)
eval("1 + 2") # 3(执行字符串表达式)三、代码实操演示
演示1:成绩等级判定器
python
"""
输入学生成绩,输出等级和评语
"""
def grade_evaluator():
name = input("请输入学生姓名: ")
score = float(input("请输入成绩 (0-100): "))
if score < 0 or score > 100:
print("❌ 成绩必须在0-100之间")
return
if score >= 90:
grade, comment = "A", "优秀!继续保持!"
elif score >= 80:
grade, comment = "B", "良好!还有进步空间"
elif score >= 70:
grade, comment = "C", "中等,需要加把劲"
elif score >= 60:
grade, comment = "D", "及格了,但远远不够"
else:
grade, comment = "F", "不及格!请认真复习!"
print(f"\n📊 {name} 的成绩报告")
print("=" * 30)
print(f"得分: {score:.1f}")
print(f"等级: {grade}")
print(f"评语: {comment}")
grade_evaluator()演示2:九九乘法表(循环嵌套)
python
def multiplication_table():
"""打印九九乘法表"""
print("=" * 50)
print(" 九九乘法表")
print("=" * 50)
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}×{i}={i * j:2d}", end=" ")
print() # 换行
multiplication_table()演示3:数据清洗与统计
python
"""
使用推导式和内置函数处理数据
"""
raw_data = " apple , banana , orange , apple , banana , apple "
items = [item.strip().lower() for item in raw_data.split(",")]
print("清洗后的列表:", items)
# 统计每种水果的数量
fruit_count = {fruit: items.count(fruit) for fruit in set(items)}
print("统计结果:", fruit_count)
# 按数量排序
sorted_fruits = sorted(fruit_count.items(), key=lambda x: x[1], reverse=True)
print("排序后的统计:")
for fruit, count in sorted_fruits:
bar = "█" * count
print(f" {fruit:8s}: {count} {bar}")四、常见错误与排错
| 错误类型 | 示例 | 原因与解决 |
|---|---|---|
| IndexError | list index out of range | 访问不存在的列表索引,检查是否越界 |
| KeyError | dict key not found | 字典中不存在该键,使用 .get() 安全访问 |
| TypeError | can only concatenate str | 类型不匹配,如 "age:" + 25,应 f"age:{25}" |
| AttributeError | 'int' object has no attribute 'append' | 调用了对象不存在的方法 |
| ValueError | invalid literal for int() | 转换非法字符串为数字,如 int("abc") |
| UnboundLocalError | local variable referenced before assignment | 在函数内使用全局变量前未声明 |
五、小结
知识图谱
数据类型与流程控制
├── 基础数据类型
│ ├── 数值型:int(任意精度)、float(IEEE754精度问题)
│ ├── 字符串:str(不可变)、bytes(二进制)
│ ├── 布尔型:bool(假值概念)
│ └── 空值:None(用 is 比较)
├── 容器类型
│ ├── list:可变有序,增删改查
│ ├── tuple:不可变有序,解包常用
│ ├── dict:键值对,哈希查找
│ └── set:无序不重复,集合运算
├── 流程控制
│ ├── 条件:if-elif-else、三元表达式
│ ├── 循环:for(遍历)、while(条件)
│ └── 控制:break/continue/else
└── 高级特性
├── 推导式:list/dict/set/generator
├── f-string:`f"{expr:format}"`
└── 内置函数:sum/len/max/min/all/any重点回顾
- Python是强类型语言,类型转换必须显式调用
- 列表推导式是Python最具标志性的语法之一,务必熟练掌握
- f-string是字符串格式化的首选方案
- 容器操作中注意区分"原地修改"和"返回新对象"的方法
六、课后练习
基础题
- 列表操作:创建一个包含10个随机整数的列表,找出最大值、最小值、总和和平均值。
- 字典操作:创建一个学生信息字典(包含姓名、年龄、成绩),添加一个新键"等级",根据成绩自动赋值A/B/C/D。
- 字符串处理:输入一段英文文本,统计其中每个单词出现的次数(忽略大小写和标点)。
进阶题
- 斐波那契数列:使用循环生成斐波那契数列的前30项,并判断每个数是否为偶数。使用列表推导式提取所有偶数项。
- 字典推导式:已知两个列表
students = ["张三", "李四", "王五"]和scores = [92, 85, 78],用字典推导式生成成绩字典,并按分数从高到低排序输出。 - 嵌套推导式:生成一个 5×5 的乘法表矩阵(嵌套列表),并使用 f-string 格式化输出为整齐的表格。
挑战题
- 简易计算器:编写一个命令行计算器,支持 + - * / % 运算,使用
while True循环,输入"exit"退出。要求能处理连续运算(如:3 + 4 * 2)。 - 数据去重与分析:输入一列数字(用逗号分隔),去除重复值并升序排列,再统计数据分布(奇数和偶数的数量、正数和负数的数量、最大和最小的差值)。
参考资料
- Python 官方文档-数据类型:https://docs.python.org/zh-cn/3/library/stdtypes.html
- Python 官方文档-内置函数:https://docs.python.org/zh-cn/3/library/functions.html
- PEP 498:f-string 规范:https://peps.python.org/pep-0498/