Python盲盒:每一页都是惊喜 1. 基础语法变量与数据类型python# 基本数据类型 name Python # 字符串 age 30 # 整数 price 99.9 # 浮点数 is_active True # 布尔值 empty None # 空值 # 查看数据类型 print(type(name)) # class str print(type(age)) # class int集合类型python# 列表 - 有序可变 fruits [apple, banana, orange] fruits.append(grape) print(fruits[0]) # apple # 元组 - 有序不可变 colors (red, green, blue) # colors[0] yellow # 会报错 # 字典 - 键值对 person { name: Alice, age: 25, city: Beijing } print(person[name]) # Alice # 集合 - 无序不重复 unique_nums {1, 2, 3, 3, 4} print(unique_nums) # {1, 2, 3, 4}2. 流程控制条件语句pythonscore 85 if score 90: grade A elif score 80: grade B elif score 70: grade C else: grade D print(f成绩等级: {grade}) # 成绩等级: B # 三元表达式 status 成人 if age 18 else 未成年循环python# for循环 for i in range(5): print(i, end ) # 0 1 2 3 4 # 遍历列表 names [张三, 李四, 王五] for index, name in enumerate(names): print(f{index}: {name}) # while循环 count 0 while count 3: print(f计数: {count}) count 1 # 列表推导式 squares [x**2 for x in range(10) if x % 2 0] print(squares) # [0, 4, 16, 36, 64]3. 函数函数定义与调用python# 基本函数 def greet(name): 简单的问候函数 return f你好, {name}! print(greet(小明)) # 你好, 小明! # 默认参数 def power(base, exponent2): return base ** exponent print(power(3)) # 9 print(power(3, 3)) # 27 # 可变参数 def sum_all(*args): return sum(args) print(sum_all(1, 2, 3, 4)) # 10 # 关键字参数 def print_info(**kwargs): for key, value in kwargs.items(): print(f{key}: {value}) print_info(nameTom, age20, city上海) # lambda函数 square lambda x: x ** 2 print(square(5)) # 254. 面向对象编程类与对象pythonclass Student: 学生类 # 类属性 school 第一中学 # 构造方法 def __init__(self, name, age, grade): self.name name # 实例属性 self.age age self.__grade grade # 私有属性 # 实例方法 def study(self, subject): return f{self.name}正在学习{subject} # 获取私有属性 def get_grade(self): return self.__grade # 类方法 classmethod def change_school(cls, new_school): cls.school new_school # 静态方法 staticmethod def is_adult(age): return age 18 # 继承 class CollegeStudent(Student): def __init__(self, name, age, grade, major): super().__init__(name, age, grade) self.major major def study(self, subject): return f{self.name}在大学研究{subject} # 使用 stu Student(小红, 16, 高一) print(stu.study(数学)) # 小红正在学习数学 print(Student.school) # 第一中学 college CollegeStudent(小刚, 20, 大二, 计算机) print(college.study(AI)) # 小刚在大学研究AI5. 文件操作python# 写入文件 with open(test.txt, w, encodingutf-8) as f: f.write(Hello Python!\n) f.write(第二行内容) # 读取文件 with open(test.txt, r, encodingutf-8) as f: content f.read() print(content) # 逐行读取 with open(test.txt, r, encodingutf-8) as f: for line in f: print(line.strip()) # 追加内容 with open(test.txt, a, encodingutf-8) as f: f.write(\n这是追加的内容)6. 异常处理pythontry: num int(input(请输入数字: )) result 10 / num print(f结果是: {result}) except ValueError: print(请输入有效的数字!) except ZeroDivisionError: print(不能除以零!) except Exception as e: print(f发生错误: {e}) else: print(没有发生异常) finally: print(无论如何都会执行) # 自定义异常 class AgeError(Exception): pass def check_age(age): if age 0: raise AgeError(年龄不能为负数) return age7. 模块与包python# 导入模块 import math import random from datetime import datetime from os import path # 使用模块 print(math.sqrt(16)) # 4.0 print(random.randint(1, 10)) # 随机1-10 print(datetime.now()) # 当前时间 print(path.exists(test.txt)) # 检查文件是否存在 # 自定义模块 (假设在 my_module.py 中) # import my_module # my_module.my_function() # __name__ 用法 if __name__ __main__: print(直接运行此文件)8. 常用内置函数python# 数据处理 numbers [3, 1, 4, 1, 5, 9, 2] print(len(numbers)) # 7 print(max(numbers)) # 9 print(min(numbers)) # 1 print(sum(numbers)) # 25 print(sorted(numbers)) # [1, 1, 2, 3, 4, 5, 9] # 类型转换 print(int(123)) # 123 print(str(456)) # 456 print(list(abc)) # [a, b, c] # 迭代工具 for i in zip([1,2,3], [a,b,c]): print(i) # (1,a) (2,b) (3,c) # 过滤器 even filter(lambda x: x%20, [1,2,3,4,5,6]) print(list(even)) # [2, 4, 6] # 映射 doubled map(lambda x: x*2, [1,2,3,4]) print(list(doubled)) # [2, 4, 6, 8]9. 装饰器python# 简单装饰器 def timer(func): import time def wrapper(*args, **kwargs): start time.time() result func(*args, **kwargs) end time.time() print(f{func.__name__} 执行时间: {end-start:.2f}秒) return result return wrapper timer def slow_function(): import time time.sleep(1) return 完成 print(slow_function()) # 会显示执行时间 # 带参数的装饰器 def repeat(times): def decorator(func): def wrapper(*args, **kwargs): for i in range(times): result func(*args, **kwargs) return result return wrapper return decorator repeat(3) def say_hello(): print(Hello!) say_hello() # 会打印3次10. 生成器与迭代器python# 生成器函数 def count_down(n): while n 0: yield n n - 1 for num in count_down(5): print(num, end ) # 5 4 3 2 1 # 生成器表达式 squares_gen (x**2 for x in range(10)) print(next(squares_gen)) # 0 print(next(squares_gen)) # 1 # 迭代器 my_list [1, 2, 3] my_iter iter(my_list) print(next(my_iter)) # 1 print(next(my_iter)) # 211. 上下文管理器python# 自定义上下文管理器 class FileManager: def __init__(self, filename, mode): self.filename filename self.mode mode self.file None def __enter__(self): self.file open(self.filename, self.mode) return self.file def __exit__(self, exc_type, exc_val, exc_tb): if self.file: self.file.close() return False # 不抑制异常 # 使用 with FileManager(example.txt, w) as f: f.write(使用上下文管理器) # 使用 contextlib 模块 from contextlib import contextmanager contextmanager def managed_file(filename, mode): f open(filename, mode) try: yield f finally: f.close() with managed_file(example2.txt, w) as f: f.write(使用contextmanager装饰器)12. 常用标准库python# 正则表达式 import re text 我的电话是 138-1234-5678 pattern r\d{3}-\d{4}-\d{4} phone re.search(pattern, text) if phone: print(phone.group()) # 138-1234-5678 # 系统操作 import os print(os.getcwd()) # 当前工作目录 os.makedirs(new_dir, exist_okTrue) # 日期时间 from datetime import datetime, timedelta now datetime.now() future now timedelta(days7) print(future.strftime(%Y-%m-%d %H:%M:%S)) # 数学运算 import random print(random.choice([1,2,3,4,5])) # 随机选择 random.shuffle([1,2,3,4,5]) # 打乱列表 # 数据处理 import json data {name: 张三, age: 30} json_str json.dumps(data) parsed json.loads(json_str)编程最佳实践命名规范python# 变量: 小写字母 下划线 user_name 张三 total_count 100 # 常量: 大写字母 下划线 MAX_CONNECTIONS 100 API_KEY your-api-key # 类名: 驼峰命名 class UserManager: pass # 函数名: 小写 下划线 def calculate_total(): pass类型注解 (Python 3.5)pythonfrom typing import List, Dict, Optional def process_data(data: List[int]) - Dict[str, int]: 处理数据并返回统计信息 return { sum: sum(data), count: len(data), max: max(data) if data else 0 } def find_user(user_id: int) - Optional[Dict]: 查找用户可能返回None if user_id 0: return {id: user_id, name: 用户} return None