Python 练习脚本(从基础到高级150个练习)
Python 练习脚本目录
基础篇 (1-50)
- 变量和数据类型
- 基本运算符
- 字符串操作
- 列表和元组
- 字典和集合
- 条件语句
- 循环结构
- 函数定义
- 文件操作
- 异常处理
进阶篇 (51-100)
- 面向对象编程
- 模块和包
- 装饰器
- 生成器
- 上下文管理器
- 正则表达式
- 日期时间处理
- 数据序列化
- 测试驱动开发
- 代码规范
高级篇 (101-150)
- 并发编程
- 网络编程
- 数据库操作
- Web开发
- 数据分析
- 机器学习
- 自动化脚本
- 性能优化
- 设计模式
- 项目实战
1. 变量和数据类型 (5个脚本)
1.1 基本数据类型.py
# 1.1 基本数据类型.py
def basic_data_types():"""演示Python基本数据类型"""# 整数age = 25year = 2024# 浮点数price = 19.99temperature = 36.6# 字符串name = "Alice"message = 'Hello World'# 布尔值is_student = Trueis_working = False# 空值empty_value = Noneprint("=== 基本数据类型 ===")print(f"整数: age={age}, year={year}")print(f"浮点数: price={price}, temperature={temperature}")print(f"字符串: name='{name}', message='{message}'")print(f"布尔值: is_student={is_student}, is_working={is_working}")print(f"空值: empty_value={empty_value}")if __name__ == "__main__":basic_data_types()
1.2 类型转换.py
# 1.2 类型转换.py
def type_conversion():"""演示类型转换"""# 字符串转数字str_num = "123"int_num = int(str_num)float_num = float(str_num)# 数字转字符串num = 456str_from_num = str(num)# 布尔转换truthy_value = bool(1) # Truefalsy_value = bool(0) # Falsefalsy_string = bool("") # False# 列表转字符串fruits = ["apple", "banana", "cherry"]fruits_str = ", ".join(fruits)print("=== 类型转换 ===")print(f"字符串转整数: int('123') = {int_num}")print(f"字符串转浮点数: float('123') = {float_num}")print(f"数字转字符串: str(456) = '{str_from_num}'")print(f"布尔转换: bool(1)={truthy_value}, bool(0)={falsy_value}")print(f"列表转字符串: {fruits_str}")if __name__ == "__main__":type_conversion()
1.3 变量命名规则.py
# 1.3 变量命名规则.py
def variable_naming():"""演示变量命名规则和规范"""# 合法的变量名my_variable = "合法"_private_var = "私有变量"camelCase = "驼峰命名"PascalCase = "帕斯卡命名"snake_case = "蛇形命名"# Python推荐使用蛇形命名user_name = "alice"user_age = 25is_active = True# 常量通常全大写MAX_SIZE = 100PI = 3.14159print("=== 变量命名规则 ===")print(f"蛇形命名: user_name = {user_name}")print(f"驼峰命名: camelCase = {camelCase}")print(f"常量: MAX_SIZE = {MAX_SIZE}, PI = {PI}")# 演示变量重新赋值counter = 10print(f"初始值: {counter}")counter = 20 # 重新赋值print(f"重新赋值后: {counter}")if __name__ == "__main__":variable_naming()
1.4 多重赋值.py
# 1.4 多重赋值.py
def multiple_assignment():"""演示多重赋值技巧"""# 同时给多个变量赋值x, y, z = 1, 2, 3print(f"多重赋值: x={x}, y={y}, z={z}")# 交换变量值a, b = 10, 20print(f"交换前: a={a}, b={b}")a, b = b, a # 交换print(f"交换后: a={a}, b={b}")# 解包序列colors = ["red", "green", "blue"]first, second, third = colorsprint(f"解包列表: first={first}, second={second}, third={third}")# 使用星号解包剩余元素numbers = [1, 2, 3, 4, 5]first_num, *middle, last_num = numbersprint(f"扩展解包: first={first_num}, middle={middle}, last={last_num}")# 字典解包person = {"name": "Bob", "age": 30}name, age = person.values()print(f"字典解包: name={name}, age={age}")if __name__ == "__main__":multiple_assignment()
1.5 数据类型检查.py
# 1.5 数据类型检查.py
def type_checking():"""演示数据类型检查和方法"""samples = [42, # 整数3.14, # 浮点数 "Hello", # 字符串True, # 布尔值[1, 2, 3], # 列表(1, 2, 3), # 元组{"key": "value"}, # 字典{1, 2, 3}, # 集合None # 空值]print("=== 数据类型检查 ===")for item in samples:print(f"值: {item:15} | 类型: {type(item).__name__:10} | 内存地址: {id(item)}")# 类型检查函数value = "123"print(f"\n类型检查:")print(f"isinstance('123', str): {isinstance(value, str)}")print(f"isinstance('123', int): {isinstance(value, int)}")# 数据类型方法num = 123print(f"\n数据类型方法:")print(f"dir(123): {[method for method in dir(num) if not method.startswith('_')][:5]}")if __name__ == "__main__":type_checking()
2. 基本运算符 (5个脚本)
# 2.1 算术运算符.py
def arithmetic_operators():"""演示算术运算符"""a, b = 10, 3print("=== 算术运算符 ===")print(f"a = {a}, b = {b}")print(f"加法: a + b = {a + b}")print(f"减法: a - b = {a - b}")print(f"乘法: a * b = {a * b}")print(f"除法: a / b = {a / b}")print(f"整除: a // b = {a // b}")print(f"取余: a % b = {a % b}")print(f"幂运算: a ** b = {a ** b}")# 复合赋值运算符x = 5print(f"\n复合赋值运算符:")print(f"初始 x = {x}")x += 3 # x = x + 3print(f"x += 3 后: {x}")x *= 2 # x = x * 2print(f"x *= 2 后: {x}")x **= 2 # x = x ** 2print(f"x **= 2 后: {x}")if __name__ == "__main__":arithmetic_operators()
2.2 比较运算符.py
# 2.2 比较运算符.py
def comparison_operators():"""演示比较运算符"""x, y = 10, 5print("=== 比较运算符 ===")print(f"x = {x}, y = {y}")print(f"等于: x == y -> {x == y}")print(f"不等于: x != y -> {x != y}")print(f"大于: x > y -> {x > y}")print(f"小于: x < y -> {x < y}")print(f"大于等于: x >= y -> {x >= y}")print(f"小于等于: x <= y -> {x <= y}")# 字符串比较str1, str2 = "apple", "banana"print(f"\n字符串比较:")print(f"'apple' == 'banana' -> {str1 == str2}")print(f"'apple' < 'banana' -> {str1 < str2}") # 按字母顺序# 链式比较age = 25print(f"\n链式比较:")print(f"18 <= age <= 60 -> {18 <= age <= 60}")if __name__ == "__main__":comparison_operators()
2.3 逻辑运算符.py
# 2.3 逻辑运算符.py
def logical_operators():"""演示逻辑运算符"""# 与运算 andprint("=== 与运算 AND ===")print(f"True and True -> {True and True}")print(f"True and False -> {True and False}")print(f"False and True -> {False and True}")print(f"False and False -> {False and False}")# 或运算 orprint("\n=== 或运算 OR ===")print(f"True or True -> {True or True}")print(f"True or False -> {True or False}")print(f"False or True -> {False or True}")print(f"False or False -> {False or False}")# 非运算 notprint("\n=== 非运算 NOT ===")print(f"not True -> {not True}")print(f"not False -> {not False}")# 实际应用age = 25has_license = Trueprint(f"\n实际应用:")print(f"年龄>=18 且有驾照: {age >= 18 and has_license}")print(f"年龄<16 或 >60: {age < 16 or age > 60}")if __name__ == "__main__":logical_operators()
2.4 位运算符.py
# 2.4 位运算符.py
def bitwise_operators():"""演示位运算符"""a, b = 5, 3 # 二进制: 5=101, 3=011print("=== 位运算符 ===")print(f"a = {a} (二进制: {bin(a)}), b = {b} (二进制: {bin(b)})")print(f"按位与: a & b = {a & b} (二进制: {bin(a & b)})")print(f"按位或: a | b = {a | b} (二进制: {bin(a | b)})")print(f"按位异或: a ^ b = {a ^ b} (二进制: {bin(a ^ b)})")print(f"按位取反: ~a = {~a} (二进制: {bin(~a)})")print(f"左移位: a << 1 = {a << 1} (二进制: {bin(a << 1)})")print(f"右移位: a >> 1 = {a >> 1} (二进制: {bin(a >> 1)})")# 实际应用:权限控制READ = 4 # 100WRITE = 2 # 010 EXECUTE = 1 # 001user_permission = READ | WRITE # 110 (6)print(f"\n权限控制应用:")print(f"用户权限: {user_permission} (二进制: {bin(user_permission)})")print(f"可读权限: {(user_permission & READ) == READ}")print(f"可执行权限: {(user_permission & EXECUTE) == EXECUTE}")if __name__ == "__main__":bitwise_operators()
2.5 身份和成员运算符.py
# 2.5 身份和成员运算符.py
def identity_membership_operators():"""演示身份和成员运算符"""# 身份运算符 is, is notprint("=== 身份运算符 ===")a = [1, 2, 3]b = [1, 2, 3]c = aprint(f"a = {a}, b = {b}, c = a")print(f"a is b -> {a is b}") # False,不同对象print(f"a is c -> {a is c}") # True,同一对象print(f"a == b -> {a == b}") # True,值相等# 小整数缓存x = 256y = 256print(f"\n小整数缓存:")print(f"x=256, y=256, x is y -> {x is y}") # True# 成员运算符 in, not inprint("\n=== 成员运算符 ===")fruits = ["apple", "banana", "cherry"]word = "hello"print(f"fruits = {fruits}")print(f"'apple' in fruits -> {'apple' in fruits}")print(f"'orange' not in fruits -> {'orange' not in fruits}")print(f"'h' in 'hello' -> {'h' in word}")print(f"'z' not in 'hello' -> {'z' not in word}")# 字典成员检查person = {"name": "Alice", "age": 25}print(f"\n字典成员检查:")print(f"'name' in person -> {'name' in person}")print(f"'city' not in person -> {'city' not in person}")if __name__ == "__main__":identity_membership_operators()
3. 字符串操作 (5个脚本)
3.1 字符串基础操作.py
# 3.1 字符串基础操作.py
def string_basics():"""演示字符串基础操作"""text = "Hello Python World"print("=== 字符串基础操作 ===")print(f"原始字符串: '{text}'")print(f"长度: {len(text)}")print(f"大写: {text.upper()}")print(f"小写: {text.lower()}")print(f"首字母大写: {text.capitalize()}")print(f"每个单词首字母大写: {text.title()}")# 索引和切片print(f"\n索引和切片:")print(f"第一个字符: '{text[0]}'")print(f"最后一个字符: '{text[-1]}'")print(f"前5个字符: '{text[:5]}'")print(f"第6到11个字符: '{text[6:12]}'")print(f"每隔一个字符: '{text[::2]}'")print(f"反转字符串: '{text[::-1]}'")# 字符串拼接str1 = "Hello"str2 = "World"result = str1 + " " + str2print(f"\n字符串拼接: '{result}'")if __name__ == "__main__":string_basics()
3.2 字符串查找和替换.py
# 3.2 字符串查找和替换.py
def string_search_replace():"""演示字符串查找和替换操作"""text = "Python is powerful, Python is easy to learn"print("=== 字符串查找 ===")print(f"文本: '{text}'")print(f"查找'Python': {text.find('Python')}")print(f"从右边查找'Python': {text.rfind('Python')}")print(f"查找'Java': {text.find('Java')}") # 返回-1print(f"索引'Python': {text.index('Python')}")print(f"计数'Python': {text.count('Python')}")print(f"\n=== 字符串替换 ===")new_text = text.replace("Python", "Java")print(f"替换后: '{new_text}'")# 多次替换multi_replace = text.replace("Python", "Java", 1) # 只替换第一个print(f"只替换第一个: '{multi_replace}'")print(f"\n=== 字符串检查 ===")test_str = "Hello123"print(f"'{test_str}' 是否以Hello开头: {test_str.startswith('Hello')}")print(f"'{test_str}' 是否以123结尾: {test_str.endswith('123')}")print(f"'{test_str}' 是否全为字母数字: {test_str.isalnum()}")if __name__ == "__main__":string_search_replace()
3.3 字符串分割和连接.py
# 3.3 字符串分割和连接.py
def string_split_join():"""演示字符串分割和连接"""# 字符串分割text = "apple,banana,cherry,orange"print("=== 字符串分割 ===")print(f"原始字符串: '{text}'")fruits = text.split(",")print(f"按逗号分割: {fruits}")# 限制分割次数limited_split = text.split(",", 2)print(f"限制分割2次: {limited_split}")# 多行文本分割multi_line = """第一行
第二行
第三行"""lines = multi_line.split("\n")print(f"多行文本分割: {lines}")print("\n=== 字符串连接 ===")# 使用join连接connected = "-".join(fruits)print(f"用-连接: '{connected}'")# 路径拼接path_parts = ["home", "user", "documents"]path = "/".join(path_parts)print(f"路径拼接: '/{path}'")# 分割行text_with_lines = "第一行\n第二行\n第三行"lines = text_with_lines.splitlines()print(f"分割行: {lines}")if __name__ == "__main__":string_split_join()
3.4 字符串格式化.py
# 3.4 字符串格式化.py
def string_formatting():"""演示字符串格式化方法"""name = "Alice"age = 25salary = 5000.50print("=== 字符串格式化 ===")# 1. % 格式化 (旧式)message1 = "姓名: %s, 年龄: %d, 工资: %.2f" % (name, age, salary)print(f"% 格式化: {message1}")# 2. str.format() 方法message2 = "姓名: {}, 年龄: {}, 工资: {:.2f}".format(name, age, salary)print(f"format方法: {message2}")# 3. f-string (推荐)message3 = f"姓名: {name}, 年龄: {age}, 工资: {salary:.2f}"print(f"f-string: {message3}")# 复杂格式化print("\n=== 复杂格式化 ===")number = 1234.5678print(f"千位分隔: {number:,.2f}")print(f"百分比: {0.256:.1%}")print(f"十六进制: {255:#x}")print(f"二进制: {10:#b}")# 对齐和填充text = "Python"print(f"\n对齐和填充:")print(f"左对齐: '{text:<10}'")print(f"右对齐: '{text:>10}'")print(f"居中对齐: '{text:^10}'")print(f"填充字符: '{text:*^10}'")if __name__ == "__main__":string_formatting()
3.5 字符串高级操作.py
# 3.5 字符串高级操作.py
def string_advanced_operations():"""演示字符串高级操作"""text = " Hello Python World! "print("=== 字符串清理 ===")print(f"原始: '{text}'")print(f"去除两端空格: '{text.strip()}'")print(f"去除左端空格: '{text.lstrip()}'")print(f"去除右端空格: '{text.rstrip()}'")# 字符串填充word = "Python"print(f"\n字符串填充:")print(f"左侧填充: '{word.ljust(10, '-')}'")print(f"右侧填充: '{word.rjust(10, '*')}'")print(f"两侧填充: '{word.center(12, '=')}'")# 字符串翻译print("\n=== 字符串翻译 ===")translation_table = str.maketrans("aeiou", "12345")test_text = "hello world"translated = test_text.translate(translation_table)print(f"翻译前: '{test_text}'")print(f"翻译后: '{translated}'")# 原始字符串print("\n=== 原始字符串 ===")normal_path = "C:\\Users\\Documents\\file.txt"raw_path = r"C:\Users\Documents\file.txt"print(f"普通字符串: {normal_path}")print(f"原始字符串: {raw_path}")# 多行字符串multi_line = """这是一个多行字符串可以包含多行内容"""print(f"多行字符串: {multi_line}")if __name__ == "__main__":string_advanced_operations()
4. 列表和元组 (5个脚本)
4.1 列表基础操作.py
# 4.1 列表基础操作.py
def list_basic_operations():"""演示列表基础操作"""# 创建列表fruits = ['apple', 'banana', 'cherry']numbers = [1, 2, 3, 4, 5]mixed = [1, 'hello', 3.14, True]print("=== 列表基础操作 ===")print(f"水果列表: {fruits}")print(f"数字列表: {numbers}")print(f"混合列表: {mixed}")# 访问元素print(f"第一个水果: {fruits[0]}")print(f"最后一个水果: {fruits[-1]}")# 切片操作print(f"前两个水果: {fruits[:2]}")print(f"从第二个开始: {fruits[1:]}")print(f"反转列表: {fruits[::-1]}")# 修改元素fruits[1] = 'blueberry'print(f"修改后: {fruits}")# 列表长度print(f"水果列表长度: {len(fruits)}")if __name__ == "__main__":list_basic_operations()
4.2 列表方法.py
# 4.2 列表方法.py
def list_methods():"""演示列表常用方法"""fruits = ['apple', 'banana', 'cherry']print("=== 列表方法 ===")# 添加元素fruits.append('orange')print(f"append后: {fruits}")fruits.insert(1, 'grape')print(f"insert后: {fruits}")# 移除元素removed = fruits.pop()print(f"pop移除: {removed}, 剩余: {fruits}")fruits.remove('banana')print(f"remove后: {fruits}")# 扩展列表more_fruits = ['mango', 'pineapple']fruits.extend(more_fruits)print(f"extend后: {fruits}")# 排序fruits.sort()print(f"排序后: {fruits}")# 反转fruits.reverse()print(f"反转后: {fruits}")# 查找索引index = fruits.index('grape')print(f"'grape'的索引: {index}")if __name__ == "__main__":list_methods()
4.3 列表推导式.py
# 4.3 列表推导式.py
def list_comprehensions():"""演示列表推导式"""# 基本列表推导式squares = [x**2 for x in range(10)]print(f"平方数: {squares}")# 带条件的列表推导式even_squares = [x**2 for x in range(10) if x % 2 == 0]print(f"偶数的平方: {even_squares}")# 多个循环的列表推导式pairs = [(x, y) for x in range(3) for y in range(3)]print(f"坐标对: {pairs}")# 使用条件表达式numbers = [1, 2, 3, 4, 5]labels = ['偶数' if x % 2 == 0 else '奇数' for x in numbers]print(f"数字标签: {labels}")# 嵌套列表推导式matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]flat = [num for row in matrix for num in row]print(f"扁平化: {flat}")if __name__ == "__main__":list_comprehensions()
4.4 元组操作.py
# 4.4 元组操作.py
def tuple_operations():"""演示元组操作"""# 创建元组fruits = ('apple', 'banana', 'cherry')single_element = (1,) # 单个元素的元组需要逗号numbers = tuple([1, 2, 3, 4, 5])print("=== 元组操作 ===")print(f"水果元组: {fruits}")print(f"单个元素元组: {single_element}")print(f"数字元组: {numbers}")# 访问元素print(f"第一个水果: {fruits[0]}")print(f"最后一个水果: {fruits[-1]}")# 切片print(f"前两个水果: {fruits[:2]}")# 元组是不可变的,以下操作会报错# fruits[0] = 'avocado' # 取消注释会报错# 元组方法count = fruits.count('apple')index = fruits.index('banana')print(f"'apple'出现次数: {count}")print(f"'banana'的索引: {index}")# 元组解包a, b, c = fruitsprint(f"元组解包: a={a}, b={b}, c={c}")# 元组连接more_fruits = ('orange', 'grape')all_fruits = fruits + more_fruitsprint(f"连接后: {all_fruits}")if __name__ == "__main__":tuple_operations()
4.5 列表和元组的比较.py
# 4.5 列表和元组的比较.py
def list_vs_tuple():"""演示列表和元组的比较"""# 性能比较import timeimport syslist_data = [1, 2, 3, 4, 5]tuple_data = (1, 2, 3, 4, 5)print("=== 列表和元组比较 ===")print(f"列表大小: {sys.getsizeof(list_data)} 字节")print(f"元组大小: {sys.getsizeof(tuple_data)} 字节")# 时间性能测试(创建)start = time.time()for _ in range(1000000):l = [1, 2, 3, 4, 5]list_time = time.time() - startstart = time.time()for _ in range(1000000):t = (1, 2, 3, 4, 5)tuple_time = time.time() - startprint(f"创建100万个列表用时: {list_time:.4f}秒")print(f"创建100万个元组用时: {tuple_time:.4f}秒")# 使用场景print("\n=== 使用场景 ===")# 列表用于可变数据student_scores = [85, 92, 78, 90]student_scores.append(88)print(f"学生成绩列表: {student_scores}")# 元组用于不可变数据days_of_week = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')print(f"星期元组: {days_of_week}")# 函数返回多个值def get_min_max(numbers):return min(numbers), max(numbers)nums = [1, 2, 3, 4, 5]min_val, max_val = get_min_max(nums)print(f"最小值: {min_val}, 最大值: {max_val}")if __name__ == "__main__":list_vs_tuple()
5. 字典和集合 (5个脚本)
5.1 字典基础操作.py
# 5.1 字典基础操作.py
def dict_basic_operations():"""演示字典基础操作"""# 创建字典person = {'name': 'Alice','age': 25,'city': 'Beijing'}print("=== 字典基础操作 ===")print(f"字典内容: {person}")# 访问元素print(f"姓名: {person['name']}")print(f"年龄: {person.get('age')}")print(f"职业: {person.get('job', '未填写')}") # 使用默认值# 修改元素person['age'] = 26person['job'] = 'Engineer' # 添加新键值对print(f"修改后: {person}")# 删除元素del person['city']removed = person.pop('job')print(f"删除后: {person}, 移除的职业: {removed}")# 遍历字典print("\n=== 遍历字典 ===")for key in person:print(f"键: {key}, 值: {person[key]}")for key, value in person.items():print(f"{key}: {value}")if __name__ == "__main__":dict_basic_operations()
5.2 字典方法.py
# 5.2 字典方法.py
def dict_methods():"""演示字典常用方法"""person = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}print("=== 字典方法 ===")# 获取所有键keys = person.keys()print(f"所有键: {list(keys)}")# 获取所有值values = person.values()print(f"所有值: {list(values)}")# 获取所有键值对items = person.items()print(f"所有键值对: {list(items)}")# 更新字典person.update({'age': 26, 'job': 'Engineer'})print(f"更新后: {person}")# 设置默认值person.setdefault('country', 'China')print(f"设置默认值后: {person}")# 清空字典person_copy = person.copy()person_copy.clear()print(f"清空后的副本: {person_copy}")# 弹出指定键age = person.pop('age')print(f"弹出年龄: {age}, 剩余: {person}")# 随机弹出一个键值对item = person.popitem()print(f"随机弹出: {item}, 剩余: {person}")if __name__ == "__main__":dict_methods()
5.3 字典推导式.py
# 5.3 字典推导式.py
def dict_comprehensions():"""演示字典推导式"""# 基本字典推导式squares = {x: x**2 for x in range(5)}print(f"平方字典: {squares}")# 带条件的字典推导式even_squares = {x: x**2 for x in range(10) if x % 2 == 0}print(f"偶数的平方: {even_squares}")# 交换键值original = {'a': 1, 'b': 2, 'c': 3}swapped = {v: k for k, v in original.items()}print(f"交换键值: {swapped}")# 合并两个列表为字典keys = ['name', 'age', 'city']values = ['Alice', 25, 'Beijing']person = {k: v for k, v in zip(keys, values)}print(f"合并为字典: {person}")# 过滤字典scores = {'Alice': 85, 'Bob': 60, 'Charlie': 75, 'David': 90}passed = {k: v for k, v in scores.items() if v >= 70}print(f"及格的学生: {passed}")if __name__ == "__main__":dict_comprehensions()
5.4 集合基础操作.py
# 5.4 集合基础操作.py
def set_basic_operations():"""演示集合基础操作"""# 创建集合fruits = {'apple', 'banana', 'cherry'}numbers = set([1, 2, 3, 4, 5])print("=== 集合基础操作 ===")print(f"水果集合: {fruits}")print(f"数字集合: {numbers}")# 添加元素fruits.add('orange')print(f"添加后: {fruits}")# 移除元素fruits.remove('banana')print(f"移除后: {fruits}")# 集合运算set1 = {1, 2, 3, 4, 5}set2 = {4, 5, 6, 7, 8}print(f"集合并: {set1 | set2}")print(f"集合交: {set1 & set2}")print(f"集合差: {set1 - set2}")print(f"集合对称差: {set1 ^ set2}")# 集合比较subset = {1, 2}print(f"{subset} 是 {set1} 的子集: {subset.issubset(set1)}")print(f"{set1} 是 {subset} 的超集: {set1.issuperset(subset)}")if __name__ == "__main__":set_basic_operations()
5.5 字典和集合的应用.py
# 5.5 字典和集合的应用.py
def dict_set_applications():"""演示字典和集合的应用"""# 使用字典计数text = "hello world hello python"words = text.split()word_count = {}for word in words:word_count[word] = word_count.get(word, 0) + 1print("=== 单词计数 ===")for word, count in word_count.items():print(f"{word}: {count}")# 使用集合去重numbers = [1, 2, 2, 3, 4, 4, 5]unique_numbers = set(numbers)print(f"\n原始列表: {numbers}")print(f"去重后: {unique_numbers}")# 字典映射print("\n=== 字典映射 ===")grades = {'Alice': 'A', 'Bob': 'B', 'Charlie': 'C'}student = 'Alice'print(f"{student} 的成绩是: {grades.get(student, '未登记')}")# 集合运算应用students_math = {'Alice', 'Bob', 'Charlie'}students_physics = {'Bob', 'David', 'Eve'}both = students_math & students_physicseither = students_math | students_physicsonly_math = students_math - students_physicsprint(f"\n同时选数学和物理: {both}")print(f"选数学或物理: {either}")print(f"只选数学: {only_math}")if __name__ == "__main__":dict_set_applications()
6. 条件语句 (5个脚本)
6.1 基本条件语句.py
# 6.1 基本条件语句.py
def basic_conditionals():"""演示基本条件语句"""age = 18print("=== 基本条件语句 ===")if age >= 18:print("你已成年")else:print("你未成年")# 多条件判断score = 85if 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}")if __name__ == "__main__":basic_conditionals()
6.2 嵌套条件语句.py
# 6.2 嵌套条件语句.py
def nested_conditionals():"""演示嵌套条件语句"""age = 25has_license = Trueprint("=== 嵌套条件语句 ===")if age >= 18:if has_license:print("可以驾驶")else:print("年龄足够但没有驾照")else:print("年龄不足,不能驾驶")# 使用逻辑运算符简化if age >= 18 and has_license:print("可以驾驶(简化版)")elif age >= 18 and not has_license:print("年龄足够但没有驾照(简化版)")else:print("年龄不足,不能驾驶(简化版)")if __name__ == "__main__":nested_conditionals()
6.3 条件表达式.py
# 6.3 条件表达式.py
def conditional_expressions():"""演示条件表达式(三元运算符)"""age = 20# 传统写法if age >= 18:status = "成年"else:status = "未成年"print(f"传统写法: {status}")# 条件表达式status = "成年" if age >= 18 else "未成年"print(f"条件表达式: {status}")# 复杂一点的条件表达式score = 75result = "及格" if score >= 60 else "不及格"print(f"分数 {score}: {result}")# 嵌套条件表达式grade = 'A' if score >= 90 else 'B' if score >= 80 else 'C' if score >= 70 else 'D' if score >= 60 else 'F'print(f"分数 {score} 对应等级: {grade}")if __name__ == "__main__":conditional_expressions()
6.4 条件语句与集合.py
# 6.4 条件语句与集合.py
def conditionals_with_collections():"""演示条件语句与集合的结合使用"""# 检查列表是否为空my_list = [1, 2, 3]if my_list:print(f"列表不为空,长度为: {len(my_list)}")else:print("列表为空")# 检查元素是否在集合中fruits = {'apple', 'banana', 'cherry'}fruit = 'apple'if fruit in fruits:print(f"{fruit} 在水果集合中")else:print(f"{fruit} 不在水果集合中")# 检查字典键是否存在person = {'name': 'Alice', 'age': 25}key = 'name'if key in person:print(f"键 '{key}' 存在,值为: {person[key]}")else:print(f"键 '{key}' 不存在")if __name__ == "__main__":conditionals_with_collections()
6.5 条件语句实战.py
# 6.5 条件语句实战.py
def conditionals_practice():"""条件语句实战应用"""# 用户身份验证username = "admin"password = "123456"if username == "admin" and password == "123456":print("登录成功")else:print("用户名或密码错误")# 数字分类number = 15if number % 2 == 0:parity = "偶数"else:parity = "奇数"if number > 0:sign = "正数"elif number < 0:sign = "负数"else:sign = "零"print(f"数字 {number} 是{parity},也是{sign}")# 闰年判断year = 2024if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):print(f"{year} 是闰年")else:print(f"{year} 不是闰年")if __name__ == "__main__":conditionals_practice()
7. 循环结构 (5个脚本)
7.1 for循环基础.py
# 7.1 for循环基础.py
def for_loop_basics():"""演示for循环基础"""# 遍历列表fruits = ['apple', 'banana', 'cherry']print("=== 遍历列表 ===")for fruit in fruits:print(fruit)# 遍历字符串text = "Python"print("\n=== 遍历字符串 ===")for char in text:print(char)# 使用rangeprint("\n=== 使用range ===")for i in range(5):print(i)print("\n=== 指定范围的range ===")for i in range(2, 6):print(i)print("\n=== 带步长的range ===")for i in range(0, 10, 2):print(i)if __name__ == "__main__":for_loop_basics()
7.2 while循环.py
# 7.2 while循环.py
def while_loop_basics():"""演示while循环"""# 基础while循环count = 0print("=== 基础while循环 ===")while count < 5:print(count)count += 1# 使用break退出循环print("\n=== 使用break ===")count = 0while True:print(count)count += 1if count >= 3:break# 使用continue跳过当前迭代print("\n=== 使用continue ===")count = 0while count < 5:count += 1if count == 3:continueprint(count)if __name__ == "__main__":while_loop_basics()
7.3 循环控制语句.py
# 7.3 循环控制语句.py
def loop_control_statements():"""演示循环控制语句"""# break示例print("=== break示例 ===")for i in range(10):if i == 5:breakprint(i)# continue示例print("\n=== continue示例 ===")for i in range(10):if i % 2 == 0:continueprint(i)# else子句print("\n=== else子句 ===")for i in range(5):print(i)else:print("循环正常结束")# 带有break的elseprint("\n=== 带有break的else ===")for i in range(5):if i == 3:breakprint(i)else:print("循环正常结束") # 不会执行,因为循环被break中断if __name__ == "__main__":loop_control_statements()
7.4 嵌套循环.py
# 7.4 嵌套循环.py
def nested_loops():"""演示嵌套循环"""# 打印乘法表print("=== 乘法表 ===")for i in range(1, 4):for j in range(1, 4):print(f"{i} * {j} = {i * j}")print() # 空行分隔# 遍历二维列表matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]print("=== 遍历二维列表 ===")for row in matrix:for element in row:print(element, end=' ')print() # 换行if __name__ == "__main__":nested_loops()
7.5 循环实战应用.py
# 7.5 循环实战应用.py
def loop_applications():"""循环实战应用"""# 计算阶乘n = 5factorial = 1for i in range(1, n + 1):factorial *= iprint(f"{n}的阶乘是: {factorial}")# 查找质数print("\n=== 查找质数 ===")for num in range(2, 20):for i in range(2, num):if num % i == 0:breakelse:print(f"{num} 是质数")# 斐波那契数列print("\n=== 斐波那契数列 ===")a, b = 0, 1count = 0while count < 10:print(a, end=' ')a, b = b, a + bcount += 1if __name__ == "__main__":loop_applications()
8. 函数定义 (5个脚本)
8.1 函数基础.py
# 8.1 函数基础.py
def function_basics():"""演示函数基础"""# 定义简单函数def greet():print("Hello, World!")# 调用函数greet()# 带参数的函数def greet_name(name):print(f"Hello, {name}!")greet_name("Alice")# 带返回值的函数def add(a, b):return a + bresult = add(3, 5)print(f"3 + 5 = {result}")if __name__ == "__main__":function_basics()
8.2 函数参数.py
# 8.2 函数参数.py
def function_parameters():"""演示函数参数"""# 位置参数def introduce(name, age):print(f"我叫{name},今年{age}岁")introduce("Alice", 25)# 关键字参数introduce(age=30, name="Bob")# 默认参数def greet(name, message="你好"):print(f"{message}, {name}!")greet("Alice")greet("Bob", "Hello")# 可变参数 *argsdef sum_all(*args):return sum(args)print(f"求和: {sum_all(1, 2, 3, 4, 5)}")# 可变关键字参数 **kwargsdef print_info(**kwargs):for key, value in kwargs.items():print(f"{key}: {value}")print_info(name="Alice", age=25, city="Beijing")if __name__ == "__main__":function_parameters()
8.3 函数返回值.py
# 8.3 函数返回值.py
def function_return_values():"""演示函数返回值"""# 返回单个值def square(x):return x * xprint(f"5的平方: {square(5)}")# 返回多个值def min_max(numbers):return min(numbers), max(numbers)nums = [1, 2, 3, 4, 5]min_val, max_val = min_max(nums)print(f"最小值: {min_val}, 最大值: {max_val}")# 返回函数def multiplier(factor):def multiply(x):return x * factorreturn multiplydouble = multiplier(2)triple = multiplier(3)print(f"双倍: {double(5)}")print(f"三倍: {triple(5)}")if __name__ == "__main__":function_return_values()
8.4 作用域和闭包.py
# 8.4 作用域和闭包.py
def scope_and_closure():"""演示作用域和闭包"""# 全局变量和局部变量global_var = "我是全局变量"def test_scope():local_var = "我是局部变量"print(f"在函数内访问全局变量: {global_var}")print(f"在函数内访问局部变量: {local_var}")test_scope()# print(local_var) # 这会报错,因为local_var是局部变量# 修改全局变量counter = 0def increment():global countercounter += 1print(f"计数器: {counter}")increment()increment()# 闭包def outer_function(x):def inner_function(y):return x + yreturn inner_functionadd_five = outer_function(5)result = add_five(3)print(f"闭包示例: 5 + 3 = {result}")if __name__ == "__main__":scope_and_closure()
8.5 递归函数.py
# 8.5 递归函数.py
def recursive_functions():"""演示递归函数"""# 阶乘递归def factorial(n):if n == 0 or n == 1:return 1else:return n * factorial(n - 1)print(f"5的阶乘: {factorial(5)}")# 斐波那契数列递归def fibonacci(n):if n <= 1:return nelse:return fibonacci(n - 1) + fibonacci(n - 2)print("斐波那契数列前10项:")for i in range(10):print(fibonacci(i), end=' ')print()# 递归目录遍历(模拟)def traverse_directory(path, depth=0):# 模拟目录结构if path == "/root":return ["/root/file1", "/root/dir1", "/root/dir2"]elif path == "/root/dir1":return ["/root/dir1/file2", "/root/dir1/file3"]elif path == "/root/dir2":return ["/root/dir2/file4"]else:return []def print_directory(path, depth=0):indent = " " * depthprint(f"{indent}{path}")children = traverse_directory(path)for child in children:print_directory(child, depth + 1)print("\n目录结构:")print_directory("/root")if __name__ == "__main__":recursive_functions()
9. 文件操作 (5个脚本)
9.1 文件读写基础.py
# 9.1 文件读写基础.py
def file_io_basics():"""演示文件读写基础"""# 写入文件with open("example.txt", "w", encoding="utf-8") as f:f.write("Hello, World!\n")f.write("这是第二行\n")f.write("这是第三行\n")print("文件写入完成")# 读取文件with open("example.txt", "r", encoding="utf-8") as f:content = f.read()print("文件内容:")print(content)# 逐行读取with open("example.txt", "r", encoding="utf-8") as f:print("\n逐行读取:")for line in f:print(line.strip())if __name__ == "__main__":file_io_basics()
9.2 文件操作模式.py
# 9.2 文件操作模式.py
def file_operation_modes():"""演示文件操作模式"""# 追加模式with open("example.txt", "a", encoding="utf-8") as f:f.write("这是追加的内容\n")print("追加完成")# 读取追加后的文件with open("example.txt", "r", encoding="utf-8") as f:print("追加后的内容:")print(f.read())# 读写模式with open("data.txt", "w+", encoding="utf-8") as f:f.write("初始内容\n")f.seek(0) # 回到文件开头content = f.read()print(f"读写模式内容: {content}")if __name__ == "__main__":file_operation_modes()
9.3 文件路径操作.py
# 9.3 文件路径操作.py
def file_path_operations():"""演示文件路径操作"""import os# 获取当前工作目录cwd = os.getcwd()print(f"当前工作目录: {cwd}")# 检查文件是否存在filename = "example.txt"if os.path.exists(filename):print(f"文件 {filename} 存在")# 获取文件大小size = os.path.getsize(filename)print(f"文件大小: {size} 字节")# 获取文件绝对路径abs_path = os.path.abspath(filename)print(f"绝对路径: {abs_path}")else:print(f"文件 {filename} 不存在")# 列出目录内容print("\n当前目录内容:")for item in os.listdir("."):print(item)if __name__ == "__main__":file_path_operations()
9.4 CSV文件操作.py
# 9.4 CSV文件操作.py
def csv_file_operations():"""演示CSV文件操作"""import csv# 写入CSV文件with open("data.csv", "w", newline="", encoding="utf-8") as f:writer = csv.writer(f)writer.writerow(["姓名", "年龄", "城市"])writer.writerow(["Alice", 25, "Beijing"])writer.writerow(["Bob", 30, "Shanghai"])writer.writerow(["Charlie", 35, "Guangzhou"])print("CSV文件写入完成")# 读取CSV文件with open("data.csv", "r", encoding="utf-8") as f:reader = csv.reader(f)print("CSV文件内容:")for row in reader:print(row)# 使用字典方式读写CSVwith open("data_dict.csv", "w", newline="", encoding="utf-8") as f:fieldnames = ["name", "age", "city"]writer = csv.DictWriter(f, fieldnames=fieldnames)writer.writeheader()writer.writerow({"name": "Alice", "age": 25, "city": "Beijing"})writer.writerow({"name": "Bob", "age": 30, "city": "Shanghai"})if __name__ == "__main__":csv_file_operations()
9.5 JSON文件操作.py
# 9.5 JSON文件操作.py
def json_file_operations():"""演示JSON文件操作"""import json# 准备数据data = {"name": "Alice","age": 25,"city": "Beijing","hobbies": ["reading", "swimming", "coding"],"is_student": False}# 写入JSON文件with open("data.json", "w", encoding="utf-8") as f:json.dump(data, f, ensure_ascii=False, indent=2)print("JSON文件写入完成")# 读取JSON文件with open("data.json", "r", encoding="utf-8") as f:loaded_data = json.load(f)print("读取的JSON数据:")print(json.dumps(loaded_data, ensure_ascii=False, indent=2))# JSON字符串操作json_str = '{"name": "Bob", "age": 30}'parsed_data = json.loads(json_str)print(f"\n解析JSON字符串: {parsed_data}")if __name__ == "__main__":json_file_operations()
10. 异常处理 (5个脚本)
10.1 基础异常处理.py
# 10.1 基础异常处理.py
def basic_exception_handling():"""演示基础异常处理"""# 捕获特定异常try:num = int(input("请输入一个数字: "))result = 10 / numprint(f"10 / {num} = {result}")except ValueError:print("错误: 请输入有效的数字!")except ZeroDivisionError:print("错误: 不能除以零!")# 捕获多个异常try:num = int(input("请再输入一个数字: "))result = 10 / numexcept (ValueError, ZeroDivisionError) as e:print(f"发生错误: {e}")else:print(f"计算成功,结果是: {result}")finally:print("程序执行完毕")if __name__ == "__main__":basic_exception_handling()
10.2 自定义异常.py
# 10.2 自定义异常.py
def custom_exceptions():"""演示自定义异常"""# 定义自定义异常class NegativeNumberError(Exception):def __init__(self, value):self.value = valuesuper().__init__(f"负数错误: {value}")class TooLargeError(Exception):pass# 使用自定义异常def process_number(n):if n < 0:raise NegativeNumberError(n)if n > 100:raise TooLargeError("数字不能大于100")return n * 2# 测试自定义异常test_numbers = [5, -3, 150, 10]for num in test_numbers:try:result = process_number(num)print(f"处理结果: {result}")except NegativeNumberError as e:print(f"捕获到负数错误: {e}")except TooLargeError as e:print(f"捕获到过大错误: {e}")if __name__ == "__main__":custom_exceptions()
10.3 异常链.py
# 10.3 异常链.py
def exception_chaining():"""演示异常链"""def open_file(filename):try:with open(filename, "r") as f:return f.read()except FileNotFoundError as e:raise RuntimeError(f"无法打开文件: {filename}") from etry:content = open_file("nonexistent.txt")except RuntimeError as e:print(f"捕获到的异常: {e}")print(f"原始异常: {e.__cause__}")if __name__ == "__main__":exception_chaining()
10.4 断言.py
# 10.4 断言.py
def assertions_demo():"""演示断言使用"""def calculate_average(numbers):assert len(numbers) > 0, "列表不能为空"assert all(isinstance(x, (int, float)) for x in numbers), "所有元素必须是数字"return sum(numbers) / len(numbers)# 测试断言test_data1 = [1, 2, 3, 4, 5]print(f"平均值: {calculate_average(test_data1)}")try:test_data2 = []calculate_average(test_data2)except AssertionError as e:print(f"断言错误: {e}")try:test_data3 = [1, 2, '3', 4]calculate_average(test_data3)except AssertionError as e:print(f"断言错误: {e}")if __name__ == "__main__":assertions_demo()
10.5 异常处理实战.py
# 10.5 异常处理实战.py
def exception_handling_practice():"""异常处理实战"""def safe_divide(a, b):try:return a / bexcept ZeroDivisionError:print("错误: 除数不能为零")return Noneexcept TypeError:print("错误: 参数类型不正确")return Nonedef get_list_element(lst, index):try:return lst[index]except IndexError:print(f"错误: 索引 {index} 超出范围")return Noneexcept TypeError:print("错误: 索引必须是整数")return None# 测试除法函数print("=== 安全除法 ===")print(safe_divide(10, 2))print(safe_divide(10, 0))print(safe_divide(10, '2'))# 测试列表访问函数print("\n=== 安全列表访问 ===")my_list = [1, 2, 3, 4, 5]print(get_list_element(my_list, 2))print(get_list_element(my_list, 10))print(get_list_element(my_list, '2'))if __name__ == "__main__":exception_handling_practice()
进阶篇点击这里