2025py重学计划
跳到导航
跳到搜索
Day 1
Day 1 Python 语法入门 变量、print、类型、输入输出 写一个 CLI 工具,输入姓名打印问候语
写一个 CLI 工具,输入姓名打印问候语
v1 cat echo.py name = 'evan' print( name + " have a good day") v2 ➜ py2025 cat echo.py name = input("please input your name") print( name + " have a good day") py echo.py please input your name evan evan have a good day ➜ py2025 cat echo.py v3 import sys if len(sys.argv) < 2: print("Usage: python echo.py <name>") else: name = sys.argv[1] print(f"Hi, {name} have a good day") ➜ py2025 py echo.py Usage: python echo.py <name> ➜ py2025 py echo.py evan Hi, evan have a good d v4 ➜ py2025 cat greet.py import argparse def main(): parser = argparse.ArgumentParser(description="Say Hi to someone") parser.add_argument("-n","--name",required=True,help="The name of the person to greet.") args = parser.parse_args() print(f"Hello,{args.name} hope you have a good day") if __name__ == "__main__": main() ➜ py2025 python greet.py -n evan Hello,evan hope you have a good day
day2
Day 2 流程控制 if, for, while, break, continue 判断磁盘使用率是否超过阈值
num = [1,2,3,4,5,6,] for nu in num: if nu % 2 == 0: print(f"{num} 偶数") continue elif nu == 5: print(f"找到 5 quit loop") break print(f"{num} 奇数")
day3
Day 3 数据结构 list, dict, set, tuple 常用操作 把 log 中的错误代码用 dict 统计次数
py2025 cat errors.log ERR001 ERR002 ERR001 ERR003 ERR002 ERR001 ➜ py2025 py 1.py ERR001: 3次 ERR002: 2次 ERR003: 1次 ➜ py2025 tail 1.py error_counts = {} with open("errors.log","r") as file: for line in file: error_code = line.strip() error_counts[error_code] = error_counts.get(error_code,0) + 1 for code,count in error_counts.items(): print(f"{code}: {count}次") 这ai 解说还真的有意思 for code, count in error_counts.items(): 这一行: error_counts 是一个字典,用于存储错误代码及其出现的次数。例如,error_counts 可能是 {"E001": 3, "E002": 2} 这样的形式。 items() 是字典的一个方法,它会返回一个包含多个元组的可迭代对象,每个元组由字典的键和对应的值组成。对于 {"E001": 3, "E002": 2} 这个字典,error_counts.items() 的结果就是 [("E001", 3), ("E002", 2)] 这样的形式。 for code, count in error_counts.items(): 是一个循环语句,code 和 count 是自定义的变量名。在每次循环中,code 会被赋值为字典的键(也就是错误代码,如 "E001"),count 会被赋值为对应的值(也就是该错误代码出现的次数,如 3)。也就是说,第一次循环时,code 是 "E001",count 是 3;第二次循环时,code 是 "E002",count 是 2。 print(f"{code}: {count} 次") 这一行: print() 是 Python 内置的函数,用于在控制台输出信息。 f"{code}: {count} 次" 是一个格式化字符串(也称为 f-string)。在这个字符串中,{code} 和 {count} 是占位符,会被 code 和 count 变量的值所替换。例如,当 code 是 "E001",count 是 3 时,f"{code}: {count} 次" 就会被解析为 "E001: 3 次",然后 print() 函数会将这个字符串输出到控制台。 第 7 行:error_code = line.strip() strip() 方法移除字符串首尾的空白字符(如换行符 \n、空格)。 示例: "E001\n".strip() → "E001" " E002 ".strip() → "E002" 第 9 行:error_counts[error_code] = error_counts.get(error_code, 0) + 1 核心逻辑:统计错误代码的出现次数。 get(key, default) 方法: 如果 key 存在于字典中,返回对应的值。 如果 key 不存在,返回默认值 default(这里是 0)。 执行过程: 第一次遇到 "E001": error_counts.get("E001", 0) 返回 0 0 + 1 = 1,因此 error_counts["E001"] = 1 第二次遇到 "E001": error_counts.get("E001", 0) 返回 1 1 + 1 = 2,因此 error_counts["E001"] = 2
day 5
Day 4 函数与作用域 定义函数、传参、返回值、局部变量 封装一个“计算服务器负载”的函数