Python知识学习02
一、注释与标准输出
作为代码的 “说明系统” 与 “交互入口”,注释和标准输出是编写可维护、可交互代码的基础,需重点掌握语法规范与灵活用法。
1.1 注释
注释是给开发人员阅读的自然语言说明,代码执行时会被跳过,核心作用是解释代码功能、便于后续维护与协作,编写代码必须添加注释。Python 支持三种注释语法,适配不同说明场景:
| 注释类型 | 语法格式 | 核心用途 | 示例代码 |
|---|---|---|---|
| 单行注释 | 以 # 开头 | 说明单个或少量几行代码 | # 定义用户账号变量 |
| 多行注释(方式 1) | 多个 # 组成 | 描述代码块整体功能 | ####################################<br># 功能:计算购物车商品总价<br>#################################### |
| 多行注释(方式 2) | 三对单引号 ''' 包裹 | 详细描述复杂逻辑 | '''<br>该代码块实现用户登录功能<br>包含账号密码输入、格式验证两步逻辑<br>''' |
| 文档注释 | 三对双引号 """ 包裹 | 自动生成项目文档 | """<br>文件名:demo02.py<br>功能:Python基础语法练习<br>""" |
1.2 标准输出 print()
1.2.1 核心语法
基础语法:print(输出内容)
1.2.2 进阶用法
-
多内容同一行输出:逗号分隔,默认空格拼接
-
取消自动换行:
end="" -
特殊字符:
\t缩进、\n换行
1.2.3 综合示
# 打印自动化运维工具界面
print("欢迎进入自动化运维工具集")
print("~ * ~ * ~ * ~ * ~ * ~ * ~")
print("\t1、清理系统垃圾文件")
print("\t2、监测CPU使用率")
print("工具版本:", "v1.0", "更新时间:2024-10")
print("执行结果:", end="")
print("成功")
2 变量:程序中的 “数据容器”
2.1 变量的本质
变量 = 存储数据的容器,通过变量名调用数据。
2.2 变量赋值
使用 = 赋值:
x = "云计算精培班"
y = 92
z = 85.5
is_valid = True
2.3 变量命名规范
-
只能由字母、数字、下划线组成
-
不能以数字开头
-
不能使用关键字
-
推荐:下划线命名 + 见名知意
2.4 特殊赋值操作
-
连续赋值:
x = y = 1 -
解包赋值:
name, age = "大牧", 18
2.5 标准输入 input()
获取用户输入,默认返回字符串:
choice = input("请输入您的选项:")
print("用户输入了:", choice)
3 数据类型:描述数据的 “本质属性”
3.1 Python 6 种基本数据类型
| 类型 | 标识 | 用途 |
|---|---|---|
| 字符串 | str | 文本信息 |
| 整数 | int | 数学运算 |
| 浮点数 | float | 小数运算 |
| 布尔 | bool | 逻辑判断 |
| 空类型 | NoneType | 无数据 |
3.2 类型查看 type()
print(type(18)) # <class 'int'>
3.3 类型转换
-
int()转整数 -
float()转浮点数 -
str()转字符串 -
bool()转布尔
注意:input() 输入必须转数字才能运算!
4 运算符:实现数据运算与逻辑判断
4.1 赋值运算符
作用:给变量赋值 / 更新值,最基础的运算符。
| 运算符 | 写法 | 等价于 | 说明 |
|---|---|---|---|
| = | a = 5 | - | 直接赋值 |
| += | a += 3 | a = a + 3 | 加后赋值 |
| -= | a -= 2 | a = a - 2 | 减后赋值 |
| *= | a *= 4 | a = a * 4 | 乘后赋值 |
| /= | a /= 2 | a = a / 2 | 除后赋值 |
| //= | a //= 2 | a = a // 2 | 整除后赋值 |
| %= | a %= 3 | a = a % 3 | 取余后赋值 |
| **= | a **= 2 | a = a ** 2 | 幂运算后赋值 |
示例代码
a = 10 # 直接赋值
a += 2 # 10 + 2 → a=12
a -= 3 # 12 - 3 → a=9
a *= 2 # 9 * 2 → a=18
a /= 3 # 18 / 3 → a=6.0
a //= 2 # 6 // 2 → a=3
a %= 2 # 3 % 2 → a=1
a **= 3 # 1 ** 3 → a=1
print(a) # 最终结果:1
4.2 算术运算符
作用:做数学计算,和我们平时的加减乘除一致。
| 运算符 | 作用 | 示例 | 结果 |
|---|---|---|---|
| + | 加法 | 5 + 3 | 8 |
| - | 减法 | 10 - 4 | 6 |
| * | 乘法 | 2 * 6 | 12 |
| / | 除法(带小数) | 7 / 2 | 3.5 |
| // | 整除(只取整数) | 7 // 2 | 3 |
| % | 取余(求余数) | 7 % 2 | 1 |
| ** | 幂运算(次方) | 2 ** 3 | 8 |
示例代码
print(10 + 3) # 13
print(10 - 3) # 7
print(10 * 3) # 30
print(10 / 3) # 3.3333333333333335
print(10 // 3) # 3
print(10 % 3) # 1
print(10 ** 3) # 1000
4.3 逻辑运算符
作用:做条件判断,返回 True(真)或 False(假)。多用于 if 判断、循环条件。
| 运算符 | 含义 | 规则 |
|---|---|---|
| and | 与 | 两边都为真,结果才为真 |
| or | 或 | 一边为真,结果就为真 |
| not | 非 | 取反,真变假,假变真 |
示例代码
a = True
b = False
print(a and b) # False(一真一假)
print(a or b) # True(一真一假)
print(not a) # False(真变假)
print(not b) # True(假变真)
# 实际使用
age = 20
print(age > 18 and age < 30) # True
print(age < 18 or age > 60) # False
4.4 比较运算符
作用:比较两个值的大小 / 是否相等,结果一定是 True 或 False。
| 运算符 | 含义 | 示例 | 结果 |
|---|---|---|---|
| == | 等于 | 5 == 5 | True |
| != | 不等于 | 5 != 3 | True |
| > | 大于 | 10 > 3 | True |
| < | 小于 | 2 < 8 | True |
| >= | 大于等于 | 5 >= 5 | True |
| <= | 小于等于 | 4 <= 6 | True |
示例代码
x = 10
y = 5
print(x == y) # False
print(x != y) # True
print(x > y) # True
print(x < y) # False
print(x >= y) # True
print(x <= y) # False
综合小练习
# 赋值 + 算术
num = 8
num += 4 # 12
num *= 2 # 24
num //= 5 # 4
# 比较 + 逻辑
print(num > 3 and num < 10) # True
print(not(num == 5)) # True
总结
-
赋值:给变量存值
=、+=、-= -
算术:做数学计算
+、-、*、/、//、%、** -
逻辑:判断真假
and、or、not -
比较:比大小 / 相等
==、!=、>、<、>=、<=
二、函数概述
1.1 什么是函数
函数本质是对生活中某个特定行为的代码封装,例如 “吃早餐”“计算加法”“用户注册” 等行为,都可以通过函数将相关代码整合在一起。
-
声明函数:定义行为的执行逻辑(代码不会立即执行,仅完成功能封装)
-
调用函数:触发行为执行(通过函数名调用,执行封装的代码逻辑)
生活场景对比示例
常规代码实现(无函数):重复编写相同逻辑,代码冗余
# 第一天吃早餐
print("早上8:00")
print("包子")
print("八宝粥")
print("咸菜")
# 执行其他任务
print("执行其他任务")
# 第二天吃早餐(重复代码)
print("早上8:00")
print("包子")
print("八宝粥")
print("咸菜")
函数改造后:代码复用,逻辑统一管理
# 声明吃早餐的函数(封装行为)
def eat():
"""吃早餐的行为(函数文档注释)"""
print("早上8:00")
print("包子")
print("八宝粥")
print("咸菜")
# 调用函数(触发行为执行)
eat() # 第一天吃早餐
print("执行其他任务")
eat() # 第二天吃早餐(直接复用)
1.2 为什么使用函数
-
代码复用:相同逻辑无需重复编写,通过函数调用直接使用
-
逻辑聚合:将相同 / 相似功能的代码集中管理,便于维护
-
可读性提升:通过函数名快速理解代码功能(见名知意)
-
扩展性强:修改功能时仅需修改函数内部代码,无需改动所有调用处
2 函数基本语法
2.1 函数声明语法
Python 中函数声明的标准格式:
def 函数名称(参数序列):
"""函数的文档注释(描述功能、参数、返回值)"""
# 函数内部执行逻辑(多行代码)
[return 返回数据] # 可选,用于返回函数执行结果
语法要素说明
| 要素 | 说明 |
|---|---|
def | 声明函数的关键字(固定语法) |
| 函数名称 | 自定义命名,遵循变量命名规则(字母、数字、下划线组成,数字不能开头),推荐下划线命名法 |
| 参数序列 | 函数执行所需的资源数据(可选),多个参数用逗号分隔 |
| 文档注释 | 用三对双引号包裹,描述函数功能、参数含义、返回值等,增强可读性 |
| 函数体 | 实现功能的核心代码,需缩进(通常 4 个空格) |
return | 返回函数执行结果(可选),执行到return后函数立即结束 |
类型描述增强语法(提升可读性)
def 函数名称(参数名: 参数类型) -> 返回值类型:
"""带类型描述的函数声明"""
函数体
return 返回值
-
作用:明确参数的数据类型和返回值类型,便于代码理解和调试
-
示例:
def get_lunch(red_packet: int) -> str表示参数为整数,返回值为字符串
2.2 函数声明案例
案例 1:无参数、无返回值(简单行为)
def close_window():
"""关窗户行为(无需参数,无需返回结果)"""
print("关闭了窗户")
案例 2:有参数、无返回值(需要资源支持的行为)
def eat_lunch(money):
"""吃午饭的行为(需要金钱参数,无需返回结果)"""
if 0 < money <= 50:
print("吃小火锅,喝点啤酒")
elif 50 < money <= 100:
print("烧烤,扎啤-多来点")
elif 100 < money <= 200:
print("全羊")
案例 3:无参数、有返回值(需要汇报结果的行为)
def call_the_roll():
"""点名行为(无需参数,返回点名结果)"""
print("点名过程...")
return "屈真,马梓淦,杨坤,吴成林" # 返回点名结果
案例 4:有参数、有返回值(需要资源且需汇报结果)
def get_lunch(red_packet: int) -> str:
"""带饭行为(需要红包参数,返回带饭结果)"""
print("带饭过程...")
result = ""
if 0 < red_packet <= 50:
result = "炒菜米饭"
elif 50 < red_packet <= 100:
result = "炒牛河"
return result # 返回带饭结果
2.3 函数调用语法
函数声明后不会自动执行,需通过函数名 + 括号调用,根据参数和返回值的不同,调用方式分为 4 种:
调用方式对比
| 调用场景 | 语法示例 | 说明 |
|---|---|---|
| 无参数、无返回值 | close_window() | 直接调用,执行函数内部逻辑 |
| 有参数、无返回值 | eat_lunch(50) | 传入实际参数(实参),执行逻辑 |
| 无参数、有返回值 | result = call_the_roll() | 用变量接收函数返回的结果 |
| 有参数、有返回值 | result = get_lunch(80) | 传入实参,用变量接收返回结果 |
| 有返回值但不接收 | get_lunch(80) | 执行逻辑但丢弃返回结果(语法合法) |
调用示例代码
# 1. 无参数、无返回值
close_window()
# 2. 有参数、无返回值
eat_lunch(60)
# 3. 无参数、有返回值(接收结果)
roll_result = call_the_roll()
print("点名结果:", roll_result)
# 4. 有参数、有返回值(接收结果)
lunch_result = get_lunch(70)
print("带饭结果:", lunch_result)
# 5. 有返回值但不接收
get_lunch(90)
3 函数参数详解
函数参数是函数执行所需的资源数据,Python 提供了多种参数类型,适配不同使用场景,核心目标是灵活传递数据 + 提升代码可读性。
3.1 位置参数(默认参数类型)
-
定义:最基础的参数类型,调用时按参数声明顺序传递实参
-
特点:实参与形参的匹配依赖位置顺序,必须一一对应
-
示例:
def add(a, b):
"""两数相加(位置参数示例)"""
return a + b
# 调用:按顺序传递参数(a=10, b=20)
result = add(10, 20)
print(result) # 输出:30
-
注意:位置参数调用时,参数个数必须与声明一致,否则报错
add(10) # 报错:缺少1个参数 add(10, 20, 30) # 报错:多余1个参数
3.2 关键字参数
-
定义:调用时通过 “参数名 = 值” 的形式传递数据,无需依赖位置
-
特点:明确参数含义,提升代码可读性;参数顺序可任意调整
-
示例:
def intro(name, age, score):
"""个人介绍(关键字参数示例)"""
print(f"姓名:{name},年龄:{age},成绩:{score}")
# 关键字参数调用(顺序可任意)
intro(name="汤姆", age=18, score=95)
intro(age=20, name="杰瑞", score=88) # 顺序调整不影响结果
3.3 强制关键字参数
-
定义:在参数列表中添加
*,*后的参数必须通过关键字形式传递 -
作用:避免后续参数因位置错误导致的逻辑问题
-
示例:
def intro(id, *, name, age, score):
"""个人介绍(强制关键字参数示例)"""
print(f"编号:{id},姓名:{name},年龄:{age},成绩:{score}")
# 正确调用:*后的参数必须用关键字形式
intro(10, name="汤姆", age=18, score=95)
# 错误调用:*后的参数用位置形式
# intro(10, "汤姆", 18, 95) # 报错:必须使用关键字参数
3.4 默认值参数
-
定义:声明参数时直接赋值,调用时可省略该参数(使用默认值)
-
特点:可选参数,降低调用复杂度;必须放在位置参数之后
-
示例:
def register(username, password, age=18):
"""用户注册(默认值参数示例)"""
print(f"账号:{username},密码:{password},年龄:{age}")
# 调用1:传递所有参数(覆盖默认值)
register("admin", "123456", 20) # 输出:年龄:20
# 调用2:省略默认值参数(使用默认值18)
register("xiaoli", "123123") # 输出:年龄:18
3.5 可变参数(*args)
-
定义:用
*args表示,可接收 0~N 个位置参数,自动封装为元组 -
适用场景:参数个数不确定时(如 “个人介绍时可添加任意附加信息”)
-
示例:
def introduction(name, *args):
"""个人介绍(可变参数示例)"""
print(f"姓名:{name}")
print(f"附加信息:{args}") # args是元组类型
for info in args:
print(" -", info)
# 调用:传递不同数量的附加参数
introduction("王婆") # 无附加参数,args=()
introduction("小潘", "女", 25) # args=("女", 25)
introduction("大朗", 30, "已婚", "卖炊饼") # args=(30, "已婚", "卖炊饼")
3.6 可变关键字参数(**kwargs)
-
定义:用
**kwargs表示,可接收 0~N 个关键字参数,自动封装为字典 -
适用场景:参数个数不确定且需要明确参数含义时
-
示例:
def introduction2(name, **kwargs):
"""个人介绍(可变关键字参数示例)"""
print(f"姓名:{name}")
print(f"详细信息:{kwargs}") # kwargs是字典类型
for key, value in kwargs.items():
print(f" - {key}:{value}")
# 调用:传递不同数量的关键字参数
introduction2("屈真") # 无详细信息,kwargs={}
introduction2("屈真", age=18, sex="男") # kwargs={"age":18, "sex":"男"}
introduction2("屈真", age=18, sex="男", address="成都") # 多关键字参数
3.7 万能参数(*args, **kwargs)
-
定义:结合
*args和**kwargs,可接收任意类型、任意数量的参数 -
适用场景:开发通用函数(如框架接口、工具函数),需兼容多种参数传递方式
-
示例:
def universal_func(*args, **kwargs):
"""万能参数示例(可接收任意参数)"""
print("位置参数(元组):", args)
print("关键字参数(字典):", kwargs)
# 调用:多种参数组合
universal_func(10, 20, name="汤姆", age=18)
# 输出:
# 位置参数(元组): (10, 20)
# 关键字参数(字典): {'name': '汤姆', 'age': 18}
注意事项
-
*args和**kwargs是约定俗成的命名,可修改,但不推荐 -
万能参数中,
*args必须在**kwargs之前
3.8 参数使用优先级
当函数同时包含多种参数时,声明顺序必须遵循:位置参数 → 默认值参数 → 强制关键字参数(*) → 可变参数(*args) → 可变关键字参数(**kwargs)
示例:
def complex_func(a, b, c=0, *, d, *args, **kwargs):
"""多种参数组合示例"""
print(f"位置参数:a={a}, b={b}")
print(f"默认值参数:c={c}")
print(f"强制关键字参数:d={d}")
print(f"可变参数:args={args}")
print(f"可变关键字参数:kwargs={kwargs}")
# 正确调用
complex_func(1, 2, 3, d=4, 5, 6, x=7, y=8)
4 函数返回值
返回值是函数执行后的结果,通过return语句返回,主要分为 3 种场景:无返回值、单个返回值、多个返回值。
4.1 无返回值
-
函数中不写
return,或仅写return(等价于return None) -
调用时无法接收有效结果(返回
None) -
示例:
def fn() -> None:
"""无返回值函数示例"""
print("这是无返回值函数")
# 调用
result = fn()
print(result) # 输出:None
4.2 单个返回值
-
最常用场景,
return后跟随一个数据(任意类型) -
调用时用一个变量接收返回结果
-
示例:
def power(x, y) -> int:
"""计算x的y次方(单个返回值示例)"""
return x ** y
# 接收返回值
result = power(10, 3)
print(result) # 输出:1000
4.3 多个返回值
-
return后用逗号分隔多个数据,Python 会自动封装为元组 -
调用时可用多个变量接收(变量个数与返回值个数一致)
-
示例:
def score_statistics(chinese, english, math):
"""成绩统计(多个返回值示例)"""
total = chinese + english + math
average = total / 3
return total, average # 自动封装为元组
# 接收多个返回值
total_score, avg_score = score_statistics(98, 80, 99)
print(f"总成绩:{total_score:.2f},平均成绩:{avg_score:.2f}")
# 输出:总成绩:277.00,平均成绩:92.33
4.4 return 的特殊作用
return不仅用于返回数据,还会立即终止函数执行(return后的代码不会运行):
def record_score(score):
"""记录成绩(return终止函数示例)"""
score = float(score)
if score <= 0 or score >= 100:
print("无效成绩")
return # 终止函数,后续代码不执行
print(f"录入成绩:{score}")
print("录入成功")
return True
# 测试无效成绩(触发return终止)
result = record_score(-20)
print("录入结果:", result) # 输出:无效成绩 → 录入结果:None
5 变量作用域(全局变量与局部变量)
变量的作用域指变量可被访问的代码范围,根据声明位置分为全局变量和局部变量:
-
全局变量:声明在函数外部的变量,作用域为整个文件(函数内外均可访问)
-
局部变量:声明在函数内部的变量,作用域仅当前函数(函数外部不可访问)
5.1 局部变量
-
定义:在函数内部声明的变量
-
作用域:仅函数内部可访问,函数执行结束后自动销毁
-
示例:
def add(a, b):
"""局部变量示例"""
result = a + b # result是局部变量
print("函数内访问局部变量:", result)
add(10, 20)
# print("函数外访问局部变量:", result) # 报错:变量未定义
-----------------------------------------------------------------
def add(a, b):
# 声明局部变量 result
result = a + b
print("函数内访问局部变量:", result) # 输出:33
return result
add(11, 22)
# print(result) # 报错:NameError(函数外部无法访问局部变量)
5.2 全局变量
-
定义:在函数外部声明的变量
-
作用域:整个程序(函数内外均可访问)
-
示例:
# 全局变量(函数外部声明)
global_var = "我是全局变量"
def print_global():
"""访问全局变量示例"""
print("函数内访问全局变量:", global_var)
# 函数外访问全局变量
print("函数外访问全局变量:", global_var)
# 函数内访问全局变量
print_global()
----------------------------------------------
# 声明全局变量
name = "大牧老师"
def fn():
"""函数内部读取全局变量"""
print(f"name: {name}") # 直接访问全局变量
def fn2():
"""另一个函数也可读取全局变量"""
print(f"姓名: {name}")
# 函数外部读取全局变量
print(f"变量: {name}") # 输出:变量: 大牧老师
fn() # 输出:name: 大牧老师
fn2() # 输出:姓名: 大牧老师
5.3 全局变量修改规则
函数内部不能直接修改全局变量的值,若需修改,需用global关键字声明:
# 声明全局变量
name = "大牧老师"
def fn():
global name # 声明:后续修改的是全局变量
name = "DAMU" # 修改全局变量
print(f"name: {name}") # 输出:name: DAMU
# 函数外部修改全局变量(直接修改,无需声明)
name = "牟文斌"
print(f"变量: {name}") # 输出:变量: 牟文斌
fn() # 执行函数修改全局变量
fn2() # 输出:姓名: DAMU(读取修改后的全局变量)
注意
-
若函数内部仅读取全局变量的值,无需
global声明 -
若函数内部声明了与全局变量同名的变量,则该变量为局部变量(覆盖全局变量)
全局变量与局部变量同名冲突
若函数内部声明了与全局变量同名的变量,则该变量为局部变量,会覆盖全局变量(仅在函数内部有效):
# 全局变量
a = 12
b = 22
def fn():
# 声明局部变量(与全局变量同名)
a = "hello"
b = "world"
c = "python" # 局部变量
print(a, b, c) # 输出:hello world python(访问局部变量)
# 位置1:函数外部访问全局变量
print(a, b) # 输出:12 22
fn() # 执行函数(内部访问局部变量)
# 位置3:函数执行后,全局变量未被修改
print(a, b) # 输出:12 22
# print(a, b, c) # 报错:NameError(c是局部变量,外部不可访问)
6 Python 内置函数
6.1 什么是内置函数
内置函数是 Python 解释器自带的函数,无需声明即可直接调用,涵盖数据处理、类型转换、逻辑判断等常用功能。
例如:
-
abs():获取绝对值 -
bin():十进制转二进制 -
hex():十进制转十六进制 -
print():标准输出
6.2 基础内置函数
6.2.1 dir():查看对象的可操作属性
-
功能:返回对象的所有属性和方法列表
-
示例:查看字符串的可操作方法
s = "hello"
print(dir(s)) # 输出字符串的所有方法(如upper()、split()等)
6.2.2 help():查看对象的帮助文档
-
功能:返回对象的详细使用说明(参数、功能、示例)
-
示例:查看
str.split()方法的用法
# 查看split()方法的帮助文档
help(str.split)
输出结果(核心部分):
split(sep=None, maxsplit=-1) method of builtins.str instance
Return a list of the substrings in the string, using sep as the separator.
# 功能:用sep作为分隔符,拆分字符串为子字符串列表
sep: 分隔符(默认None,按任意空白字符拆分)
maxsplit: 最大拆分次数(默认-1,无限制)
6.3 常见内置函数分类汇总
6.3.1数据转换类
用于不同数据类型之间的转换,是日常开发中最基础的操作。
| 函数名 | 功能说明 | 示例代码 | 输出结果 |
|---|---|---|---|
abs(x) | 获取数字的绝对值(支持整数、浮点数) | abs(-10.5) | 10.5 |
bin(x) | 十进制整数转二进制字符串(带 0b 前缀) | bin(10) | "0b1010" |
hex(x) | 十进制整数转十六进制字符串(带 0x 前缀) | hex(255) | "0xff" |
oct(x) | 十进制整数转八进制字符串(带 0o 前缀) | oct(8) | "0o10" |
int(x) | 其他类型转整数(支持字符串、浮点数,字符串需为纯数字) | int("123")、int(3.8) | 123、3 |
float(x) | 其他类型转浮点数 | float("3.14")、float(5) | 3.14、5.0 |
str(x) | 其他类型转字符串 | str(123)、str(True) | "123"、"True" |
bool(x) | 其他类型转布尔值(0 / 空字符串 / None / 空容器→False;非 0 / 非空→True) | bool(0)、bool("hello") | False、True |
chr(x) | ASCII 码转字符(x 为 0-127 整数) | chr(65) | "A" |
ord(x) | 字符转 ASCII 码(x 为单个字符) | ord("a") | 97 |
6.3.2 序列操作类(列表 / 字符串 / 元组通用)
用于处理序列型数据(字符串、列表、元组等),简化遍历、排序、统计等操作。
| 函数名 | 功能说明 | 示例代码 | 输出结果 |
|---|---|---|---|
len(x) | 获取序列长度(字符数、元素个数) | len("hello")、len([1,2,3]) | 5、3 |
max(x) | 获取序列中的最大值(支持数字、字符串按 ASCII 排序) | max([3,1,4])、max("abc") | 4、"c" |
min(x) | 获取序列中的最小值 | min([3,1,4])、min("abc") | 1、"a" |
sum(x) | 计算序列中元素的总和(仅支持数字序列) | sum([1,2,3,4]) | 10 |
sorted(x) | 对序列排序(默认升序,返回新列表;原序列不变) | sorted([3,1,4])、sorted("cba") | [1,3,4]、["a","b","c"] |
reversed(x) | 反转序列(返回迭代器,需转列表查看) | list(reversed([1,2,3])) | [3,2,1] |
enumerate(x) | 遍历序列时返回(索引,元素)元组(适合需要索引的循环) | list(enumerate(["a","b"])) | [(0,"a"), (1,"b")] |
slice(start, end, step) | 生成切片对象(简化序列截取) | lst = [1,2,3,4]; lst[slice(1,3)] | [2,3] |
6.3.3 逻辑判断类(条件筛选 / 验证)
用于判断序列或多个值的逻辑关系,简化条件判断代码。
| 函数名 | 功能说明 | 示例代码 | 输出结果 |
|---|---|---|---|
all(x) | 序列中所有元素为 True 才返回 True(空序列默认 True) | all([True, 1, "a"])、all([True, 0]) | True、False |
any(x) | 序列中任意元素为 True 就返回 True(空序列默认 False) | any([False, 0, ""])、any([False, 1]) | False、True |
isinstance(x, type) | 判断 x 是否为指定类型(支持多类型判断) | isinstance(5, int)、isinstance("a", (str,int)) | True、True |
6.3.4 数学运算类(简化数值计算)
无需导入 math 模块即可使用的基础数学功能。
| 函数名 | 功能说明 | 示例代码 | 输出结果 |
|---|---|---|---|
pow(x, y) | 计算 x 的 y 次方(等价于 x**y,支持整数、浮点数) | pow(2,3)、pow(4, 0.5) | 8、2.0 |
round(x, n) | 四舍五入(x 为数值,n 为保留小数位数,默认 0) | round(3.1415)、round(3.1415, 2) | 3、3.14 |
divmod(x, y) | 同时返回 x 除以 y 的商和余数(等价于 (x//y, x%y)) | divmod(10, 3) | (3, 1) |
6.3.5 对象操作类(查看 / 判断对象)
用于查看对象的属性、类型、内存地址等,便于调试。
| 函数名 | 功能说明 | 示例代码 | 输出结果 |
|---|---|---|---|
id(x) | 获取对象的内存地址(整数标识) | id("hello") | 140709443259888(示例值) |
type(x) | 获取对象的类型(返回类型对象) | type(5)、type([1,2]) | <class 'int'>、<class 'list'> |
dir(x) | 查看对象的所有可操作属性和方法(返回列表) | dir("hello") | 包含 upper()、split() 等方法 |
help(x) | 查看对象的帮助文档(详细说明功能、参数) | help(str.split) | 输出 split() 方法的使用说明 |
callable(x) | 判断对象是否可调用(函数、方法→True;普通变量→False) | callable(print)、callable(5) | True、False |
6.3.6 程序控制类(调试 / 退出)
用于程序调试、退出等控制操作。
| 函数名 | 功能说明 | 示例代码 | 备注 |
|---|---|---|---|
print(x) | 标准输出(可输出多个值,默认空格分隔、换行结尾) | print("hello", 123) | 输出 hello 123 并换行 |
input(x) | 标准输入(接收用户输入,返回字符串类型) | name = input("请输入姓名:") | 等待用户输入,将输入内容赋值给 name |
exit()/quit() | 退出程序(任意位置执行立即终止) | exit() | 终端 / 脚本直接退出 |
breakpoint() | 设置程序断点(调试时暂停,进入交互模式) | breakpoint() | 需配合调试工具使用 |
6.3.7 高级内置函数
用于复杂数据处理(过滤、映射、整合等),简化高阶逻辑。
| 函数名 | 功能说明 | 示例代码 | 输出结果 |
|---|---|---|---|
filter(func, x) | 按条件筛选序列(func 为判断函数,返回 True 保留元素) | list(filter(lambda x: x>3, [1,4,2,5])) | [4,5] |
map(func, x) | 序列映射(func 为处理函数,对每个元素执行操作) | list(map(lambda x: x*2, [1,2,3])) | [2,4,6] |
zip(*x) | 多序列打包(将多个序列的对应元素组成元组,长度取最短序列) | list(zip([1,2], ["a","b"])) | [(1,"a"), (2,"b")] |
eval(x) | 执行字符串中的 Python 表达式(仅支持简单表达式,慎用不可信字符串) | eval("1+2*3")、eval('"a"+"b"') | 7、"ab" |
exec(x) | 执行字符串中的 Python 代码(支持多行代码,无返回值) | exec("a=1; print(a+2)") | 输出 3 |
6.3.8 汇总
| 类别 | 函数名 | 功能说明 |
|---|---|---|
| 数据转换 | abs() | 获取数字的绝对值 |
bin() | 十进制转二进制字符串(带0b前缀) | |
hex() | 十进制转十六进制字符串(带0x前缀) | |
oct() | 十进制转八进制字符串(带0o前缀) | |
int() | 其他类型转整数 | |
float() | 其他类型转浮点数 | |
str() | 其他类型转字符串 | |
bool() | 其他类型转布尔值(0 / 空字符串 / None→False,非 0 / 非空→True) | |
| 序列操作 | len() | 获取序列长度(字符串、列表、元组等) |
max() | 获取序列中的最大值 | |
min() | 获取序列中的最小值 | |
sum() | 计算序列中元素的总和 | |
sorted() | 对序列排序(返回新列表) | |
reversed() | 反转序列(返回迭代器) | |
enumerate() | 遍历序列时返回(索引,元素)元组 | |
| 逻辑判断 | all() | 序列中所有元素为 True 则返回 True |
any() | 序列中任意元素为 True 则返回 True | |
| 数学运算 | pow(x, y) | 计算 x 的 y 次方(等价于x**y) |
round(x, n) | 四舍五入,n 为保留小数位数 | |
divmod(x, y) | 返回(x//y, x% y)元组(整除结果和余数) | |
| 对象操作 | id() | 获取对象的内存地址 |
type() | 获取对象的类型 | |
isinstance() | 判断对象是否为指定类型 | |
| 输入输出 | print() | 标准输出 |
input() | 标准输入(接收字符串) | |
| 程序控制 | exit()/quit() | 退出程序 |
breakpoint() | 程序断点调试 |
6.4 内置函数使用示例
示例 1:数据转换
print(abs(-10)) # 输出:10(绝对值)
print(bin(10)) # 输出:0b1010(十进制转二进制)
print(hex(255)) # 输出:0xff(十进制转十六进制)
print(int("123")) # 输出:123(字符串转整数)
示例 2:序列操作
lst = [3, 1, 4, 1, 5]
print(len(lst)) # 输出:5(长度)
print(max(lst)) # 输出:5(最大值)
print(sorted(lst)) # 输出:[1, 1, 3, 4, 5](排序)
print(list(enumerate(lst))) # 输出:[(0,3), (1,1), (2,4), (3,1), (4,5)]
示例 3:逻辑判断
print(all([True, 1, "hello"])) # 输出:True(所有元素为真)
print(all([True, 0, "hello"])) # 输出:False(存在0)
print(any([False, 0, ""])) # 输出:False(所有元素为假)
print(any([False, 0, "hello"])) # 输出:True(存在非假元素)
示例 4:数学运算
print(pow(2, 3)) # 输出:8(2的3次方)
print(round(3.1415, 2)) # 输出:3.14(四舍五入保留2位小数)
print(divmod(10, 3)) # 输出:(3, 1)(10//3=3,10%3=1)
7 函数编码规范
7.1 函数命名规范
-
采用下划线命名法:多个单词用下划线连接(如
user_register) -
见名知意:通过函数名直接理解功能(如
calculate_score表示计算成绩) -
避免使用关键字和内置函数名(如
def print():会覆盖内置print函数)
7.2 文档注释规范
函数必须添加文档注释,说明以下内容:
-
函数功能
-
参数含义(类型、作用)
-
返回值(类型、含义)
-
示例(复杂函数)
示例:
def calculate_taxi_fare(km: float) -> float:
"""
计算打车费用(起步价8元/3公里,超3公里后每公里2元)
参数:
km: 行驶公里数(必须为正数)
返回值:
float: 应付车费
"""
if km <= 0:
raise ValueError("公里数必须为正数")
return 8.0 if km <=3 else 8.0 + (km-3)*2.0
7.3 什么时候该用函数
-
代码逻辑需要重复使用时(避免冗余)
-
代码块逻辑复杂(超过 10 行),需要拆分简化时
-
多个地方使用相同逻辑,需要统一维护时
-
功能需要对外提供接口时(如工具函数、框架接口)
7.4 函数设计原则
-
单一职责:一个函数只实现一个核心功能(便于维护和复用)
-
参数精简:仅保留必要参数,可选参数用默认值(降低调用复杂度)
-
返回明确:返回值类型统一,避免返回多种类型(如有时返回 int,有时返回 str)
-
异常处理:对非法参数进行判断,抛出明确异常
三、异常:容错机制
异常处理是 Python 中保障程序不崩溃、稳定运行的核心机制,专门用来处理代码运行时可能出现的错误(如除零错误、文件不存在、类型错误、索引越界等),让程序具备容错能力,即使出错也能优雅提示、继续执行。
1 什么是异常?
程序运行时出现的错误就是异常(比如:除以 0、打开不存在的文件、访问列表不存在的索引、类型不匹配等)。如果不处理异常,程序会直接崩溃终止;使用异常处理,程序可以捕获错误 → 处理错误 → 继续运行。
2 异常处理核心语法(完整版)
2.1 最基础语法(捕获所有异常)
try:
# 可能会出错的代码
except:
# 出错后执行的容错代码
示例
try:
print(10 / 0) # 除以0,一定会报错
except:
print("出错啦!不能除以零") # 捕获错误,程序不崩溃
2.2 标准完整语法(最常用)
try:
# 可能出错的代码
except 异常类型1:
# 处理类型1的错误
except 异常类型2:
# 处理类型2的错误
else:
# 没有出错时执行的代码
finally:
# 无论是否出错,一定会执行的代码
3 四大模块详细解释
1. try 块
-
存放可能抛出异常的代码
-
一旦出错,立即跳转到对应
except -
不出错则正常执行完毕
2. except 块(捕获异常)
-
出错时执行
-
可以捕获指定类型的异常(推荐)
-
也可以捕获所有异常(不推荐)
3. else 块(可选)
-
代码没有出错才会执行
-
常用来处理 “成功逻辑”
4. finally 块(可选)
-
无论是否出错,无论是否捕获,最终 100% 执行
-
常用于:关闭文件、关闭数据库、释放资源
4 最常用完整示例
try:
a = int(input("请输入数字:"))
b = int(input("请输入另一个数字:"))
res = a / b
# 捕获除以0错误
except ZeroDivisionError:
print("错误:不能除以零!")
# 捕获不是数字的错误
except ValueError:
print("错误:请输入有效数字!")
# 其他未知错误
except Exception as e:
print("未知错误:", e)
# 没出错才执行
else:
print("计算结果:", res)
# 无论是否出错,都会执行
finally:
print("程序执行完毕,资源已释放")
5 Python 常见异常类型
| 异常名称 | 触发场景 |
|---|---|
SyntaxError | 语法错误 |
NameError | 使用未定义变量 |
TypeError | 类型不匹配 |
ValueError | 值类型错误 |
ZeroDivisionError | 除以 0 |
IndexError | 列表索引越界 |
KeyError | 字典键不存在 |
FileNotFoundError | 文件不存在 |
Exception | 所有异常的基类(万能捕获) |
6 高级用法
1. 捕获异常并获取错误信息
try:
print(10 / 0)
except Exception as e:
print("异常类型:", type(e))
print("异常信息:", e)
2. 一个 except 捕获多种异常
try:
# code
except (ZeroDivisionError, ValueError, TypeError) as e:
print("出错:", e)
3. 主动抛出异常(raise)
自己手动触发异常,常用于数据校验。
age = int(input("请输入年龄:"))
if age < 0 or age > 150:
raise ValueError("年龄必须在0-150之间")
4. 自定义异常
class MyError(Exception):
pass
try:
raise MyError("这是我自定义的异常")
except MyError as e:
print(e)
异常处理执行流程总结
-
try 代码不出错try → else → finally
-
try 代码出错try → 匹配 except → finally
-
无论如何finally 一定执行(最可靠的资源释放位置)
为什么要用异常处理?
-
防止程序崩溃
-
给用户友好提示
-
保证关键代码(关闭文件、数据库)一定执行
-
提高程序稳定性、健壮性
try:
可能出错代码
except:
出错处理
else:
不出错执行
finally:
必须执行(关闭资源)
总结
-
try:放风险代码 -
except:捕获并处理错误 -
else:无错误时执行 -
finally:无论如何都执行(关闭文件 / 连接必备) -
优先捕获具体异常,少用万能
except -
是程序稳定运行的必备容错机制
四、 容器模块练习(list、tuple、set、dict)
1.1 IP 地址追加与打印
ip_adds = ["192.168.0.10","192.168.0.23"]
ip_adds.append("192.168.0.46")
ip_adds.extend(["192.168.0.68", "192.168.0.70"])
print("当前接入IP:", ip_adds)
1.2 邮件地址列表维护
email_lst = ['admin@aliyun.com', 'mwb@openedu.com', 'damu@aliyun.com', 'laoliu@126.com', 'wang@openedu.com', 'xxy@openedu.com', 'px@openedu.com']
new_emails = ['xiaoming@163.com','zhangxp@aliyun.com','wu@126.com','sunyp@openedu.com']
for e in new_emails:
email_lst.insert(0, e)
if len(email_lst) > 10:
email_lst.pop()
print("最近邮件列表:", email_lst)
1.3 服务器存储 TB 转 GB
server_disks = [1, 2.6, 1.2, 0.8, 3]
gb_disks = [i*1024 for i in server_disks]
print("GB单位存储:", gb_disks)
1.4 3 天网络流量统计
traffic_data = [ [300, 80, 120, 260,100], [280, 90, 100, 288, 90], [220, 70, 120, 240, 100]]
all_data = []
for day in traffic_data:
all_data.extend(day)
print("3天流量峰值:", max(all_data))
print("3天流量谷值:", min(all_data))
1.5 服务器访问次数统计
access_record = ['data1', 'serv1', 'data1', 'serv2', 'serv1', 'data2', 'data1', 'serv3', 'data3', 'data1', 'serv1']
count = {}
for host in access_record:
count[host] = count.get(host, 0)+1
max_host = max(count, key=count.get)
print("访问最多主机:", max_host)
1.6 公共云服务查询
cloud1 = {'HC(Huawei Cloud)', 'AWS(Amazon Web Service)', 'OC(Oracle Cloud)', 'MZ(Microsoft Azure)', 'GCP(Google Cloud Platform)'}
cloud2 = {'AC(Alibaba Cloud)', 'TC(Tencent Cloud)', 'HC(Huawei Cloud)', 'MZ(Microsoft Azure)', 'OC(Oracle Cloud)'}
print("公共服务:", cloud1 & cloud2)
1.7 服务标签去重
serv_lst = ['ECX', 'CLOUD', 'CONTAINER', 'STORAGE', 'DB', 'NET', 'PERM', 'CONTAINER', 'DB', 'ECX', 'DB', 'PERM', 'NET', 'ECX', 'CLOUD', 'NET', 'PERM', 'PERM']
unique_serv = list(set(serv_lst))
print("去重后服务:", unique_serv)
1.8 CPU 使用率不同值提取
t1 = [0.0, 0.0, 0.0, 0.0, 0.4, 0.0, 0.0, 1.9, 0.0, 0.0, 0.0, 0.0, 3.8, 3.7, 1.0, 0.1, 1.8, 0.2, 0.1, 4.4]
t2 = [0.0, 0.0, 0.0, 0.0, 1.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.6, 0.0, 1.2, 0.0, 1.2, 1.2, 0.0, 0.0]
t3 = [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.9, 2.9, 1.9, 0.0, 5.8, 1.0, 2.9, 0.0]
all_cpu = set(t1+t2+t3)
print("所有不同CPU值:", all_cpu)
1.9 服务器错误信息对比
f1 = {'power failure', 'disk error', 'network issue', 'network timeout'}
f2 = {'power failure', 'power holdon', 'disk locked', 'disk timeout', 'disk error'}
print("共同问题:", f1 & f2)
print("差异问题:", f1 ^ f2)
print("所有问题:", f1 | f2)
1.10 提取交换机名称
topologies = [('router1', ['switch1', 'switch2']), ('router2', ['switch3', 'switch4'])]
switches = set()
for router, sws in topologies:
switches.update(sws)
print("交换机集合:", switches)
1.11 提取用户网络协议
user_protocols = {'user1': ['TCP', 'UDP', 'TCP'], 'user2': ['ICMP', 'TCP']}
protocols = set()
for user, pros in user_protocols.items():
protocols.update(pros)
print("所有协议:", protocols)
1.12 服务器故障次数统计
fault_reports = {('server1', 'power failure'), ('server2', 'hard disk error'), ('server1', 'network issue')}
fault_count = {}
for server, fault in fault_reports:
fault_count[server] = fault_count.get(server, 0)+1
print("故障统计:", fault_count)
1.13 存储容量 TB 转 GB
server_configs = {'server1': {'cpu': 'Intel i7', 'ram': '16GB', 'storage': '1TB'}, 'server2': {'cpu': 'AMD Ryzen 9', 'ram': '32GB', 'storage': '2TB'}}
storage_gb = {}
for k,v in server_configs.items():
tb = float(v['storage'].replace('TB',''))
storage_gb[k] = f"{tb*1024}GB"
print("存储GB:", storage_gb)
1.14 平均流量计算
traffic_data = [('morning', [100, 200, 150]), ('afternoon', [300, 400, 350]), ('evening', [250, 300, 280])]
avg_traffic = {}
for t, lst in traffic_data:
avg_traffic[t] = sum(lst)/len(lst)
print("平均流量:", avg_traffic)
1.15 设备端口总和
device_ports = {'router1': [80, 443, 22], 'switch1': [1000, 2000, 3000]}
port_sum = {k:sum(v) for k,v in device_ports.items()}
print("端口总和:", port_sum)
1.16 服务可用率
service_availabilities = [('service1', [True, False, True]), ('service2', [False, True, True])]
rate = {}
for s, lst in service_availabilities:
rate[s] = sum(lst)/len(lst)
print("可用率:", rate)
1.17 可用 IP 数量
subnet_ips = [('192.168.1.0/24', ['192.168.1.10', '192.168.1.20', '192.168.1.30']), ('10.0.0.0/16', ['10.0.0.50', '10.0.1.100'])]
ip_count = {k:len(v) for k,v in subnet_ips}
print("可用IP数量:", ip_count)
1.18 访问来源数量
visit_sources = {('www.example1.com', 'Google'), ('www.example2.com', 'Bing'), ('www.example1.com', 'Facebook')}
source_count = {}
for site, source in visit_sources:
if site not in source_count:
source_count[site] = set()
source_count[site].add(source)
result = {k:len(v) for k,v in source_count.items()}
print("来源数量:", result)
1.19 连接设备数量
server_devices = [('server1', ['device1', 'device2']), ('server2', ['device3', 'device4'])]
dev_count = {k:len(v) for k,v in server_devices}
print("设备数量:", dev_count)
1.20 端口安全等级分组
port_security = {80: 'low', 443: 'medium', 22: 'high'}
sec_group = {}
for port, sec in port_security.items():
if sec not in sec_group:
sec_group[sec] = []
sec_group[sec].append(port)
print("安全分组:", sec_group)
1.21 服务 - 服务器映射
server_services = [('server1', ['web', 'db', 'mail']), ('server2', ['file', 'print'])]
service_servers = {}
for server, services in server_services:
for s in services:
if s not in service_servers:
service_servers[s] = []
service_servers[s].append(server)
print("服务服务器:", service_servers)
1.22 流量超标用户筛选
user_traffics = {'user1': {'upload': 500, 'download': 1000}, 'user2': {'upload': 300, 'download': 800}}
result = [u for u, t in user_traffics.items() if t['upload']+t['download']>1000]
print("流量超标用户:", result)
1.23 网站访问次数统计
visit_logs = {('www.example1.com', '2023-09-01 10:00'), ('www.example2.com', '2023-09-01 11:00'), ('www.example1.com', '2023-09-01 12:00')}
visit_count = {}
for site, t in visit_logs:
visit_count[site] = visit_count.get(site,0)+1
print("访问次数:", visit_count)
1.24 亚洲 IP 段提取
ip_regions = {'192.168.0.0 - 192.168.0.255': 'Asia', '10.0.0.0 - 10.0.0.255': 'Europe'}
asia_ips = [ip for ip,reg in ip_regions.items() if reg=='Asia']
print("亚洲IP段:", asia_ips)
1.25 低延迟路由器筛选
latencies = [('router1', [10, 15, 20]), ('router2', [5, 8, 12])]
low_latency = [r for r,lst in latencies if sum(lst)/len(lst)<10]
print("低延迟路由:", low_latency)
1.26 设备数量排序
device_types = {'router': 5, 'switch': 10, 'firewall': 3}
sorted_dev = sorted(device_types.items(), key=lambda x:x[1], reverse=True)
sorted_list = [d[0] for d in sorted_dev]
print("设备排序:", sorted_list)
1.27 最长访问网站
visit_records = {'user1': [('www.example1.com', 10), ('www.example2.com', 20)], 'user2': [('www.example3.com', 15), ('www.example4.com', 25)]}
max_visit = {}
for user, records in visit_records.items():
max_site = max(records, key=lambda x:x[1])
max_visit[user] = max_site[0]
print("最长访问:", max_visit)
1.28 高负载服务器筛选
server_performances = {'server1': {'cpu_usage': 80, 'memory_usage': 70, 'disk_usage': 50}, 'server2': {'cpu_usage': 90, 'memory_usage': 80, 'disk_usage': 60}}
high_load = [s for s,perf in server_performances.items() if perf['cpu_usage']>80 and perf['memory_usage']>80]
print("高负载服务器:", high_load)
五、字符串练习
1.1 字符串转大写
s = "Hello, World!"
print(s.upper())
1.2 去除两端空格
text = " Python is great! "
print(text.strip())
1.3 字符串拼接
str1 = "Hello"
str2 = "World"
print(str1 + str2)
1.4 按逗号分割
s = "apple,banana,cherry"
print(s.split(","))
1.5 查找子串位置
message = "I love Python programming"
print(message.find("Python"))
1.6 提取数字
data = "123abc456"
num = ''.join([c for c in data if c.isdigit()])
print(num)
1.7 切片前 10 个字符
sentence = "This is a long sentence."
print(sentence[:10])
1.8 提取邮箱域名
text = "hello@python.com"
print(text.split("@")[1])
1.9 判断是否全字母
code = "PYTHON123"
print(code.isalpha())
1.10 字符替换
phrase = "How are you?"
print(phrase.replace("o", "*"))
1.11 提取服务器名称数字
server_name = "cloud-server-01"
num = ''.join([c for c in server_name if c.isdigit()])
print(num)
1.12 判断私有 IP
ip = "192.168.1.100"
parts = list(map(int, ip.split(".")))
is_private = (parts[0]==10) or (parts[0]==172 and 16<=parts[1]<=31) or (parts[0]==192 and parts[1]==168)
print("是否私有IP:", is_private)
1.13 替换下划线为空格
provider = "AWS_Cloud"
print(provider.replace("_", " "))
1.14 提取协议主版本号
protocol = "HTTP/1.1"
print(protocol.split("/")[1][0])
1.15 子网掩码转二进制
mask = "255.255.255.0"
binary = '.'.join([bin(int(x))[2:].zfill(8) for x in mask.split('.')])
print(binary)
1.16 判断字符串长度
bucket_name = "my-cloud-bucket"
print("长度超过20:", len(bucket_name)>20)
1.17 提取设备品牌
device_model = "Router-ASUS-RT-AC88U"
print(device_model.split("-")[1])
1.18 出现次数最多的单词
description = "This cloud service provides high-speed data transfer and low latency."
words = description.replace(".","").split()
word_count = {}
for w in words:
word_count[w] = word_count.get(w,0)+1
max_word = max(word_count, key=word_count.get)
print("最多单词:", max_word)
1.19 提取顶级域名
domain = "www.example.com"
print("."+domain.split(".")[-1])
1.20 提取 IP 地址
error_message = "Connection timed out for IP 10.10.10.10"
import re
ip = re.findall(r'\d+\.\d+\.\d+\.\d+', error_message)[0]
print(ip)
六、os /sys 模块练习
1.1 获取当前工作目录
import os
print(os.getcwd())
1.2 创建新目录
import os
os.mkdir("new_directory")
1.3 删除空目录
import os
os.rmdir("empty_directory")
1.4 获取 Python 版本
import sys
print(sys.version)
1.5 遍历当前目录
import os
print(os.listdir("."))
1.6 获取命令行参数
import sys
print(sys.argv)
1.7 切换工作目录
import os
os.chdir("target_directory")
1.8 获取模块搜索路径
import sys
print(sys.path)
1.9 文件重命名
import os
os.rename("old_file.txt", "new_file.txt")
1.10 获取脚本名称
import sys
print(sys.argv[0])
七 datetime 模块练习
1.1 当前时间格式化
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
1.2 星期判断
from datetime import datetime
now = datetime.now()
print("今天周几:", now.weekday()+1)
1.3 5 天后时间
from datetime import datetime, timedelta
now = datetime.now()
future = now + timedelta(days=5)
print(future.strftime("%Y-%m-%d %H:%M:%S"))
八、hashlib /hmac 练习
1.1 MD5 加密
import hashlib
s = "Hello World"
md5 = hashlib.md5(s.encode()).hexdigest()
print(md5)
1.2 文件 SHA256 计算
import hashlib
def file_sha256(path):
sha = hashlib.sha256()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
sha.update(chunk)
return sha.hexdigest()
print(file_sha256("example.txt"))
1.3 10 次迭代 MD5
import hashlib
pwd = "123456"
for i in range(10):
pwd = hashlib.md5(pwd.encode()).hexdigest()
print(pwd)
1.4 带盐值迭代加密
import hashlib
def n_md5(s, n):
for i in range(n):
s = hashlib.md5((s+str(i)).encode()).hexdigest()
return s
print(n_md5("123456", 5))
九、subprocess 模块练习
1.1 查看网卡信息
import subprocess
result = subprocess.run('ipconfig', capture_output=True, text=True, shell=True)
print(result.stdout)
1.2 查看 Python 版本
import subprocess
result = subprocess.run(['python', '--version'], capture_output=True, text=True)
print(result.stdout.strip())
1.3 执行脚本传参
import subprocess
subprocess.run(['python', 'script.py', 'arg1', 'arg2'])
1.4 批量 IP 探测
import sys
import subprocess
if __name__ == "__main__":
start_ip = sys.argv[1]
end_ip = sys.argv[2]
root = start_ip.rsplit('.',1)[0]
s = int(start_ip.rsplit('.',1)[1])
e = int(end_ip.rsplit('.',1)[1])
for i in range(s, e+1):
ip = f"{root}.{i}"
res = subprocess.run(['ping', '-n', '1', ip], capture_output=True)
print(f"{ip} 畅通" if res.returncode==0 else f"{ip} 阻塞")
十、urllib 模块练习
1.1 网页数据采集
from urllib.request import Request, urlopen
url = "https://www.biquge.com"
headers = {"User-Agent":"Mozilla/5.0"}
req = Request(url, headers=headers)
resp = urlopen(req)
print(resp.read().decode('utf-8'))
1.2 天气数据采集
from urllib.request import Request, urlopen
weather_url = "https://dhrest-static.2345.com/api/v1/tqpc/getWeatherDaily?areaType=2&areaId=56294&start=2024-11-03&end=2024-11-05"
headers = {"User-Agent":"Mozilla/5.0"}
req = Request(weather_url, headers=headers)
resp = urlopen(req)
data = resp.read().decode('unicode_escape')
print(data)
十一、logging 模块练习
1.1 DEBUG 日志输出控制台
import logging
logging.basicConfig(level=logging.DEBUG, format='%(message)s')
logging.debug("debug log")
1.2 自定义 INFO 日志
import logging
logger = logging.getLogger("my_logger")
logger.setLevel(logging.INFO)
console = logging.StreamHandler()
logger.addHandler(console)
logger.info("info log")
1.3 分级日志输出
import logging
logger = logging.getLogger("my_logger")
console = logging.StreamHandler()
console.setLevel(logging.INFO)
file_handler = logging.FileHandler("log.txt")
file_handler.setLevel(logging.WARNING)
logger.addHandler(console)
logger.addHandler(file_handler)
logger.warning("warning log")
十二、GUI 模块练习(tkinter)
1.1 登录窗口实现
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.title("登录窗口")
root.geometry("300x200")
label_user = tk.Label(root, text="账号:")
label_user.grid(row=0, column=0, padx=20, pady=30, sticky="w")
entry_user = tk.Entry(root, width=20)
entry_user.grid(row=0, column=1, padx=20, pady=30)
entry_user.insert(0, "admin")
label_pwd = tk.Label(root, text="密码:")
label_pwd.grid(row=1, column=0, padx=20, pady=0, sticky="w")
entry_pwd = tk.Entry(root, width=20, show="*")
entry_pwd.grid(row=1, column=1, padx=20, pady=0)
entry_pwd.insert(0, "123456")
def login():
user = entry_user.get()
pwd = entry_pwd.get()
if user == "admin" and pwd == "123456":
messagebox.showinfo("成功", "登录成功!")
else:
messagebox.showerror("错误", "账号或密码错误!")
btn_login = tk.Button(root, text="登录", command=login)
btn_login.grid(row=2, column=1, padx=20, pady=20, sticky="e")
root.mainloop()
1.2 文件浏览器窗口
import tkinter as tk
from tkinter import Listbox, Scrollbar, messagebox
import os
import subprocess
root = tk.Tk()
root.title("文件浏览器")
root.geometry("600x400")
current_dir = os.getcwd()
scrollbar = Scrollbar(root)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
file_list = Listbox(root, yscrollcommand=scrollbar.set, font=("Arial", 12))
file_list.pack(expand=True, fill=tk.BOTH, padx=10, pady=10)
scrollbar.config(command=file_list.yview)
def load_files(dir_path):
file_list.delete(0, tk.END)
try:
files = os.listdir(dir_path)
for file in files:
file_path = os.path.join(dir_path, file)
if os.path.isdir(file_path):
file_list.insert(tk.END, f"[文件夹] {file}/")
else:
file_list.insert(tk.END, f"[文件] {file}")
except Exception as e:
messagebox.showerror("错误", f"读取目录失败:{str(e)}")
def open_selected(event):
selected_idx = file_list.curselection()
if not selected_idx:
return
selected_text = file_list.get(selected_idx[0])
if selected_text.startswith("[文件夹]"):
file_name = selected_text.replace("[文件夹] ", "").rstrip("/")
file_path = os.path.join(current_dir, file_name)
global current_dir
current_dir = file_path
load_files(current_dir)
else:
file_name = selected_text.replace("[文件] ", "")
file_path = os.path.join(current_dir, file_name)
try:
if os.name == "nt":
os.startfile(file_path)
else:
subprocess.run(["open", file_path])
except Exception as e:
messagebox.showerror("错误", f"打开文件失败:{str(e)}")
file_list.bind("<Double-Button-1>", open_selected)
load_files(current_dir)
root.mainloop()
十三、 邮件发送模块练习
1.1 发送简单文本邮件
import smtplib
from email.mime.text import MIMEText
smtp_server = "smtp.qq.com"
smtp_port = 465
email_user = "your_qq_email@qq.com"
email_pass = "your_auth_code"
sender = email_user
receiver = "target_email@example.com"
msg = MIMEText("这是Python自动发送的测试邮件", "plain", "utf-8")
msg["From"] = sender
msg["To"] = receiver
msg["Subject"] = "Python测试邮件(纯文本)"
try:
server = smtplib.SMTP_SSL(smtp_server, smtp_port)
server.login(email_user, email_pass)
server.sendmail(sender, receiver, msg.as_string())
server.quit()
print("纯文本邮件发送成功!")
except Exception as e:
print(f"发送失败:{str(e)}")
1.2 发送 HTML 格式邮件
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import parseaddr, formataddr
def _format_addr(name_addr):
name, addr = parseaddr(name_addr)
return formataddr((Header(name, "utf-8").encode(), addr))
smtp_server = "smtp.qq.com"
smtp_port = 465
email_user = "your_qq_email@qq.com"
email_pass = "your_auth_code"
sender = _format_addr(f"发送者 <{email_user}>")
receiver = _format_addr(f"接收者 <target_email@example.com>")
html_content = """
<h1>Python HTML邮件测试</h1>
<p>这是一封带HTML格式的邮件</p>
"""
msg = MIMEText(html_content, "html", "utf-8")
msg["From"] = sender
msg["To"] = receiver
msg["Subject"] = Header("Python测试邮件(HTML格式)", "utf-8")
try:
server = smtplib.SMTP_SSL(smtp_server, smtp_port)
server.login(email_user, email_pass)
server.sendmail(email_user, "target_email@example.com", msg.as_string())
server.quit()
print("HTML格式邮件发送成功!")
except Exception as e:
print(f"发送失败:{str(e)}")
1.3 发送带附件的邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.header import Header
import os
smtp_server = "smtp.qq.com"
smtp_port = 465
email_user = "your_qq_email@qq.com"
email_pass = "your_auth_code"
sender = email_user
receiver = "target_email@example.com"
msg = MIMEMultipart()
msg["From"] = sender
msg["To"] = receiver
msg["Subject"] = Header("Python测试邮件(带附件)", "utf-8")
msg.attach(MIMEText("这是带附件的测试邮件", "plain", "utf-8"))
attachment_path = "Python基础笔记.pdf"
try:
with open(attachment_path, "rb") as f:
part = MIMEBase("application", "octet-stream")
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header("Content-Disposition", f"attachment; filename={os.path.basename(attachment_path)}")
msg.attach(part)
except Exception as e:
print(f"读取附件失败:{str(e)}")
exit()
try:
server = smtplib.SMTP_SSL(smtp_server, smtp_port)
server.login(email_user, email_pass)
server.sendmail(sender, receiver, msg.as_string())
server.quit()
print("带附件邮件发送成功!")
except Exception as e:
print(f"发送失败:{str(e)}")
十四、基础语法综合练习(函数 + 条件 + 循环)
1.1 计算车费
def calculate_taxi_fare(km):
try:
km = float(km)
if km <= 0:
print("错误:公里数必须为正数!")
return False
if km <= 3:
fare = 8.0
else:
fare = 8.0 + (km - 3) * 2.0
print(f"行驶 {km} 公里,应付车费:¥{fare:.2f}")
return fare
except ValueError:
print("错误:请输入有效的数字!")
return False
km_input = input("请输入行驶公里数:")
calculate_taxi_fare(km_input)
1.2 整数各位求和
def sum_digits(n):
try:
n = int(n)
if not (0 <= n <= 1000):
print("错误:数字必须在 0~1000 之间!")
return False
total = sum(int(digit) for digit in str(n))
print(f"数字 {n} 的各位数字之和:{total}")
return total
except ValueError:
print("错误:请输入有效的整数!")
return False
num_input = input("请输入 0~1000 之间的整数:")
sum_digits(num_input)
1.3 分钟转年天
def convert_minutes_to_years_days(minutes):
try:
minutes = int(minutes)
if minutes < 0:
print("错误:分钟数不能为负数!")
return (0, 0)
total_days = minutes // (24 * 60)
years = total_days // 365
days = total_days % 365
print(f"{years} 年 {days} 天")
return (years, days)
except ValueError:
print("错误:请输入有效的整数!")
return (0, 0)
min_input = input("请输入分钟数:")
convert_minutes_to_years_days(min_input)
1.4 回文素数
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5)+1, 2):
if n % i == 0:
return False
return True
def is_palindrome(n):
return str(n) == str(n)[::-1]
def get_palindrome_primes(count=100):
res = []
num = 2
while len(res) < count:
if is_prime(num) and is_palindrome(num):
res.append(num)
num += 1
return res
primes = get_palindrome_primes(100)
for i in range(0,100,10):
print(" ".join(map(str, primes[i:i+10])))
1.5 双素数
def get_twin_primes(limit=1000):
twin_primes = []
for num in range(3, limit-1, 2):
if is_prime(num) and is_prime(num+2):
twin_primes.append((num, num+2))
return twin_primes
print(get_twin_primes(1000))
1.6 堆叠相加
def stack_sum(a, n):
try:
a, n = int(a), int(n)
total = 0
current = 0
for i in range(n):
current = current*10 + a
total += current
print("结果:", total)
return total
except:
print("输入错误")
return 0
a_input, n_input = input("请输入a和n:").split()
stack_sum(a_input, n_input)
1.7 密码强度检测
def check_password_strength(password):
if len(password) <8:
print("长度不足8位")
return False
if not password.isalnum():
print("包含非法字符")
return False
if sum(1 for c in password if c.isdigit()) <2:
print("数字不足2个")
return False
if sum(1 for c in password if c.isupper()) <2:
print("大写字母不足2个")
return False
print("密码强度:Yes")
return True
pwd = input("请输入密码:")
check_password_strength(pwd)
十五、拓展作业
1.1 斐波那契数列
def fibonacci_iter(n):
a,b =1,1
for _ in range(3,n+1):
a,b = b,a+b
return b
n = int(input("请输入n:"))
print("结果:", fibonacci_iter(n))
1.2 密码加密解密
def encrypt_password(password, offset=4):
res = []
for c in password:
new_ascii = ord(c)+offset
if new_ascii>126:
new_ascii = 32 + (new_ascii-127)
res.append(chr(new_ascii))
return "".join(res)
def decrypt_password(password, offset=4):
res = []
for c in password:
new_ascii = ord(c)-offset
if new_ascii<32:
new_ascii = 126 - (31-new_ascii)
res.append(chr(new_ascii))
return "".join(res)
text = input("请输入明文:")
offset = int(input("偏移量:"))
enc = encrypt_password(text, offset)
print("加密:", enc)
print("解密:", decrypt_password(enc, offset))
1.3 进制转换工具
def decimal_to_binary(decimal):
return bin(int(decimal))
def decimal_to_hex(decimal):
return hex(int(decimal))
def binary_to_decimal(binary):
return int(binary,2)
def hex_to_decimal(hex_str):
return int(hex_str,16)
print("1 十进制转二进制")
print("2 十进制转十六进制")
print("3 二进制转十进制")
print("4 十六进制转十进制")
choice = input("请选择:")
if choice=="1":
print(decimal_to_binary(input("十进制:")))
elif choice=="2":
print(decimal_to_hex(input("十进制:")))
elif choice=="3":
print(binary_to_decimal(input("二进制:")))
elif choice=="4":
print(hex_to_decimal(input("十六进制:")))
更多推荐



所有评论(0)