Python 编程基础学习笔记
学习者笔记
January 13, 2026
本笔记涵盖 Python 编程的核心概念,
从基础语法到高级特性,适合初学者系统学习。
Python 编程基础学习笔记 2
Contents
1 Python 简介 3
1.1 什么是 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Python 的应用领域 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 安装 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 基础语法 4
2.1 第一个 Python 程序 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2 变量与数据类型 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.3 类型转换 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3 运算符 5
3.1 算术运算符 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.2 比较运算符 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.3 逻辑运算符 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
4 数据结构 6
4.1 列表 (List) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
4.2 元组 (Tuple) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
4.3 字典 (Dictionary) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
4.4 集合 (Set) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
5 控制流 8
5.1 条件语句 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
5.2 循环语句 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
6 函数 10
6.1 定义和调用函数 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
6.2 Lambda 表达式 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
6.3 装饰器 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
7 面向对象编程 12
7.1 类的定义 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
7.2 继承 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
8 文件操作 14
8.1 读写文本文件 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
8.2 处理 JSON 文件 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
9 异常处理 15
9.1 try-except 结构 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
10 常用模块 16
10.1 os 模块 - 操作系统接口 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
10.2 datetime 模块 - 日期时间 . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
学习笔记
Python 编程基础学习笔记 3
11 总结与学习建议 17
11.1 Python 学习路线 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
11.2 学习资源推荐 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
11.3 编程最佳实践 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
学习笔记
Python 编程基础学习笔记 4
1 Python 简介
1.1 什么是 Python
Python 是一种高级、解释型、通用编程语言,由 Guido van Rossum 于 1991 年创建。
Python 的设计哲学强调代码的可读性和简洁性,其语法允许程序员用更少的代码表达
概念。
Python 的特点
• 简单易学:语法清晰,适合初学者
• 解释型语言:无需编译,直接运行
• 跨平台:支持 Windows、Mac、Linux 等
• 丰富的库:拥有大量第三方库
• 开源免费:社区活跃,资源丰富
1.2 Python 的应用领域
Python 在多个领域都有广泛应用:
1. Web 开发:Django、Flask 等框架
2. 数据科学:Pandas、NumPy、Matplotlib
3. 人工智能:TensorFlow、PyTorch
4. 自动化运维:脚本编写、系统管理
5. 爬虫开发:Scrapy、Requests
6. 游戏开发:Pygame
1.3 安装 Python
从官网 [Link] 下载对应系统的安装包。安装完成后,在命令行输入:
1 python --version
2 # 输 出 : Python 3.x.x
学习笔记
Python 编程基础学习笔记 5
2 基础语法
2.1 第一个 Python 程序
经典的 Hello World 程序:
1 # 这是一个注释
2 print ("Hello , World !")
3 print (" 你 好 , Python ! ")
2.2 变量与数据类型
Python 是动态类型语言,不需要显式声明变量类型。
1 # 数字类型
2 age = 25 # 整 数 int
3 height = 1.75 # 浮 点 数 float
4 complex_num = 3 + 4j # 复 数 complex
5
6 # 字符串类型
7 name = " Python " # 字 符 串 str
8 message = ' 学 习 笔 记 '
9
10 # 布尔类型
11 is_student = True # 布 尔 bool
12 is_working = False
13
14 # 空值
15 nothing = None # NoneType
2.3 类型转换
1 # 类型转换函数
2 num_str = "123"
3 num_int = int( num_str ) # 字符串转整数
4 num_float = float ( num_str ) # 字 符 串 转 浮 点 数
5
6 age = 25
7 age_str = str(age) # 数字转字符串
8
9 # 查看类型
10 print (type( num_int )) # <class 'int '>
学习笔记
Python 编程基础学习笔记 6
3 运算符
3.1 算术运算符
1 a, b = 10, 3
2
3 print (a + b) # 加 法 : 13
4 print (a - b) # 减 法: 7
5 print (a * b) # 乘 法 : 30
6 print (a / b) # 除 法 : 3.333...
7 print (a // b) # 整 除: 3
8 print (a % b) # 取 余: 1
9 print (a ** b) # 幂 运 算 : 1000
3.2 比较运算符
1 x, y = 5, 10
2
3 print (x == y) # 等 于 : False
4 print (x != y) # 不 等 于 : True
5 print (x > y) # 大 于 : False
6 print (x < y) # 小 于 : True
7 print (x >= y) # 大 于 等 于 : False
8 print (x <= y) # 小 于 等 于 : True
3.3 逻辑运算符
1 a, b = True , False
2
3 print (a and b) # 逻 辑 与 : False
4 print (a or b) # 逻 辑 或 : True
5 print (not a) # 逻 辑 非 : False
学习笔记
Python 编程基础学习笔记 7
4 数据结构
4.1 列表 (List)
列表是 Python 中最常用的数据结构,可以存储任意类型的元素。
1 # 创建列表
2 fruits = [" 苹 果 ", " 香 蕉 ", " 橙 子 "]
3 numbers = [1, 2, 3, 4, 5]
4 mixed = [1, " hello ", 3.14 , True]
5
6 # 访问元素
7 print ( fruits [0]) # 苹果
8 print ( fruits [ -1]) # 橙 子 (最 后 一 个)
9
10 # 列表切片
11 print ( numbers [1:4]) # [2, 3, 4]
12 print ( numbers [::2]) # [1, 3, 5]
13
14 # 列表方法
15 fruits . append (" 葡 萄 ") # 添加元素
16 fruits . insert (1, " 梨 ") # 插入元素
17 fruits . remove (" 香 蕉 ") # 删除元素
18 fruits .pop () # 弹出最后一个
19 fruits .sort () # 排序
20 fruits . reverse () # 反转
21
22 # 列表推导式
23 squares = [x**2 for x in range (10)]
24 evens = [x for x in range (20) if x % 2 == 0]
4.2 元组 (Tuple)
元组是不可变的序列,创建后不能修改。
1 # 创建元组
2 point = (3, 4)
3 colors = (" 红 ", " 绿 ", " 蓝 ")
4 single = (1,) # 单 元 素 元 组 需 要 逗 号
5
6 # 元组解包
7 x, y = point
8 print (f"x={x}, y={y}")
9
10 # 元组作为函数返回值
11 def get_min_max ( numbers ):
12 return min( numbers ), max( numbers )
13
14 minimum , maximum = get_min_max ([1 , 5, 3, 9, 2])
学习笔记
Python 编程基础学习笔记 8
4.3 字典 (Dictionary)
字典是键值对的集合,用于存储关联数据。
1 # 创建字典
2 student = {
3 "name": " 张 三 ",
4 "age": 20,
5 " major ": " 计 算 机 科 学 "
6 }
7
8 # 访问和修改
9 print ( student ["name"]) # 张三
10 student ["age"] = 21 # 修改值
11 student [" grade "] = "A" # 添加新键
12
13 # 字典方法
14 keys = student .keys () # 获取所有键
15 values = student . values () # 获取所有值
16 items = student .items () # 获取键值对
17
18 # 安全访问
19 score = student .get(" score ", 0) # 不存在返回默认值
20
21 # 遍历字典
22 for key , value in student . items ():
23 print (f"{key }: {value }")
24
25 # 字典推导式
26 squares = {x: x**2 for x in range (5)}
4.4 集合 (Set)
集合是无序的、不重复的元素集合。
1 # 创建集合
2 fruits = {" 苹 果 ", " 香 蕉 ", " 橙 子 "}
3 numbers = set ([1, 2, 2, 3, 3, 3]) # {1, 2, 3}
4
5 # 集合操作
6 fruits .add(" 葡 萄 ")
7 fruits . remove (" 香 蕉 ")
8
9 # 集合运算
10 a = {1, 2, 3, 4}
11 b = {3, 4, 5, 6}
12
13 print (a | b) # 并 集 : {1, 2, 3, 4, 5, 6}
14 print (a & b) # 交 集 : {3, 4}
15 print (a - b) # 差 集 : {1, 2}
16 print (a ^ b) # 对 称 差 集: {1, 2, 5, 6}
学习笔记
Python 编程基础学习笔记 9
5 控制流
5.1 条件语句
1 # if -elif -else 结 构
2 score = 85
3
4 if score >= 90:
5 grade = "A"
6 elif score >= 80:
7 grade = "B"
8 elif score >= 70:
9 grade = "C"
10 elif score >= 60:
11 grade = "D"
12 else:
13 grade = "F"
14
15 print (f" 成 绩 等 级 : { grade }")
16
17 # 三元表达式
18 result = " 及 格 " if score >= 60 else " 不 及 格 "
19
20 # 嵌套条件
21 age = 25
22 has_license = True
23
24 if age >= 18:
25 if has_license :
26 print (" 可 以 驾 驶 ")
27 else:
28 print (" 请 先 考 取 驾 照 ")
29 else:
30 print (" 年 龄 不 足 ")
5.2 循环语句
1 # for 循 环
2 for i in range (5):
3 print (i, end=" ") # 0 1 2 3 4
4
5 # 遍历列表
6 fruits = [" 苹 果 ", " 香 蕉 ", " 橙 子 "]
7 for fruit in fruits :
8 print (fruit )
9
10 # 带索引遍历
11 for index , fruit in enumerate ( fruits ):
12 print (f"{ index }: {fruit }")
13
学习笔记
Python 编程基础学习笔记 10
14 # while 循 环
15 count = 0
16 while count < 5:
17 print (count )
18 count += 1
19
20 # break 和 continue
21 for i in range (10):
22 if i == 3:
23 continue # 跳 过 3
24 if i == 7:
25 break # 到7停 止
26 print (i)
学习笔记
Python 编程基础学习笔记 11
6 函数
6.1 定义和调用函数
1 # 基本函数定义
2 def greet(name):
3 """ 向 指 定 的 人 打 招 呼 """
4 return f" 你 好 , {name }!"
5
6 message = greet(" Python ")
7 print ( message )
8
9 # 带默认参数的函数
10 def power(base , exponent =2):
11 return base ** exponent
12
13 print (power (3)) # 9
14 print (power (3, 3)) # 27
15
16 # 可变参数
17 def sum_all (* args):
18 return sum(args)
19
20 print ( sum_all (1, 2, 3, 4, 5)) # 15
21
22 # 关键字参数
23 def print_info (** kwargs ):
24 for key , value in kwargs . items ():
25 print (f"{key }: {value }")
26
27 print_info (name=" 张 三 ", age =20 , city=" 北 京 ")
6.2 Lambda 表达式
1 # 匿名函数
2 square = lambda x: x ** 2
3 add = lambda a, b: a + b
4
5 print ( square (5)) # 25
6 print (add (3, 4)) # 7
7
8 # 配合内置函数使用
9 numbers = [1, 5, 3, 9, 2, 7]
10 sorted_nums = sorted (numbers , key= lambda x: -x)
11 filtered = list( filter ( lambda x: x > 4, numbers ))
12 doubled = list(map( lambda x: x * 2, numbers ))
学习笔记
Python 编程基础学习笔记 12
6.3 装饰器
装饰器是 Python 的高级特性,用于修改函数的行为。
1 import time
2
3 # 定义装饰器
4 def timer(func):
5 def wrapper (* args , ** kwargs ):
6 start = [Link] ()
7 result = func (* args , ** kwargs )
8 end = [Link] ()
9 print (f"{func. __name__ } 执 行 时 间 : {end -start :.4f} 秒 ")
10 return result
11 return wrapper
12
13 # 使用装饰器
14 @timer
15 def slow_function ():
16 [Link] (1)
17 return " 完 成 "
18
19 result = slow_function ()
20
21 # 带参数的装饰器
22 def repeat ( times ):
23 def decorator (func):
24 def wrapper (* args , ** kwargs ):
25 for _ in range ( times ):
26 result = func (* args , ** kwargs )
27 return result
28 return wrapper
29 return decorator
30
31 @repeat (3)
32 def say_hello ():
33 print (" Hello !")
学习笔记
Python 编程基础学习笔记 13
7 面向对象编程
7.1 类的定义
1 class Student :
2 """ 学 生 类 """
3
4 # 类变量
5 school = " Python 大 学 "
6
7 def __init__ (self , name , age , major ):
8 """ 初 始 化 方 法 """
9 [Link] = name # 实例变量
10 [Link] = age
11 self. major = major
12 self. _score = 0 # 私 有 变 量 (约 定)
13
14 def study(self , subject ):
15 """ 学 习 方 法 """
16 return f"{[Link]} 正 在 学 习 { subject }"
17
18 def introduce (self):
19 """ 自 我 介 绍 """
20 return f" 我 是 {[Link]} , {[Link]} 岁 , 专 业 是 {[Link] }"
21
22 @property
23 def score(self):
24 """ 成 绩 属 性 """
25 return self. _score
26
27 @score . setter
28 def score(self , value ):
29 if 0 <= value <= 100:
30 self. _score = value
31 else:
32 raise ValueError (" 分 数 必 须 在 0 -100 之 间 ")
33
34 # 创建实例
35 student1 = Student (" 张 三 ", 20, " 计 算 机 科 学 ")
36 print ( student1 . introduce ())
37 print ( student1 .study (" Python "))
学习笔记
Python 编程基础学习笔记 14
7.2 继承
1 class Person :
2 """ 人 类 基 类 """
3 def __init__ (self , name , age):
4 [Link] = name
5 [Link] = age
6
7 def speak(self):
8 return f"{[Link]} 在 说 话 "
9
10 class Teacher ( Person ):
11 """ 教 师 类 , 继 承 自 Person """
12 def __init__ (self , name , age , subject ):
13 super (). __init__ (name , age) # 调 用 父 类 构 造
14 self. subject = subject
15
16 def teach(self):
17 return f"{[Link]} 正 在 教 授 {self. subject }"
18
19 def speak(self): # 方 法 重 写
20 return f" 老 师 {[Link]} 在 讲 课 "
21
22 class Student ( Person ):
23 """ 学 生 类 """
24 def __init__ (self , name , age , grade ):
25 super (). __init__ (name , age)
26 self. grade = grade
27
28 def study(self):
29 return f"{[Link]} 在 学 习 , 目 前 {[Link] } 年 级 "
30
31 # 多态示例
32 def introduce ( person ):
33 print ( person .speak ())
34
35 teacher = Teacher (" 李 老 师 ", 35, " Python ")
36 student = Student (" 小 明 ", 18, " 大 一 ")
37
38 introduce ( teacher ) # 老师李老师在讲课
39 introduce ( student ) # 小明在说话
学习笔记
Python 编程基础学习笔记 15
8 文件操作
8.1 读写文本文件
1 # 写入文件
2 with open(" example .txt", "w", encoding ="utf -8") as f:
3 f. write(" 第 一 行 内 容 \n")
4 f. write(" 第 二 行 内 容 \n")
5 f. writelines ([" 第 三 行 \n", " 第 四 行 \n"])
6
7 # 读取文件
8 with open(" example .txt", "r", encoding ="utf -8") as f:
9 content = [Link] () # 读取全部
10 # 或者
11 lines = f. readlines () # 读取所有行
12 # 或者
13 for line in f: # 逐行读取
14 print (line. strip ())
15
16 # 追加内容
17 with open(" example .txt", "a", encoding ="utf -8") as f:
18 f. write(" 追 加 的 内 容 \n")
8.2 处理 JSON 文件
1 import json
2
3 # 写 入 JSON
4 data = {
5 "name": " Python 课 程 ",
6 " students ": [" 张 三 ", " 李 四 ", " 王 五 "],
7 "info": {"level ": " 入 门 ", " hours ": 40}
8 }
9
10 with open("[Link]", "w", encoding ="utf -8") as f:
11 [Link](data , f, ensure_ascii =False , indent =2)
12
13 # 读 取 JSON
14 with open("[Link]", "r", encoding ="utf -8") as f:
15 loaded_data = [Link](f)
16
17 # JSON 字 符 串 转 换
18 json_str = [Link] (data , ensure_ascii = False )
19 parsed = [Link]( json_str )
学习笔记
Python 编程基础学习笔记 16
9 异常处理
9.1 try-except 结构
1 # 基本异常处理
2 try:
3 result = 10 / 0
4 except ZeroDivisionError :
5 print (" 除 数 不 能 为 零 ! ")
6
7 # 捕获多种异常
8 try:
9 num = int(input (" 请 输 入 数 字 : "))
10 result = 100 / num
11 except ValueError :
12 print (" 请 输 入 有 效 的 数 字 ")
13 except ZeroDivisionError :
14 print (" 除 数 不 能 为 零 ")
15 except Exception as e:
16 print (f" 发 生 错 误 : {e}")
17 finally :
18 print (" 无 论 如 何 都 会 执 行 ")
19
20 # 主动抛出异常
21 def validate_age (age):
22 if age < 0:
23 raise ValueError (" 年 龄 不 能 为 负 数 ")
24 if age > 150:
25 raise ValueError (" 年 龄 不 合 理 ")
26 return True
27
28 # 自定义异常
29 class CustomError ( Exception ):
30 def __init__ (self , message ):
31 self. message = message
32 super (). __init__ (self. message )
33
34 try:
35 raise CustomError (" 这 是 自 定 义 错 误 ")
36 except CustomError as e:
37 print (e. message )
学习笔记
Python 编程基础学习笔记 17
10 常用模块
10.1 os 模块 - 操作系统接口
1 import os
2
3 # 路径操作
4 current_dir = os. getcwd () # 当前目录
5 [Link] ("/path/to/dir") # 切换目录
6 os. makedirs ("new/path", exist_ok =True) # 创 建 目 录
7
8 # 文件操作
9 os. rename ("[Link]", "[Link]") # 重命名
10 os. remove ("[Link]") # 删除文件
11 [Link]. exists ("[Link]") # 检查存在
12 [Link]. isfile ("[Link]") # 是否为文件
13 [Link]. isdir(" folder ") # 是否为目录
14
15 # 路径处理
16 path = [Link](" folder ", "[Link]")
17 dirname = [Link]. dirname (path)
18 basename = [Link]. basename (path)
19 name , ext = [Link]. splitext ("[Link]")
10.2 datetime 模块 - 日期时间
1 from datetime import datetime , timedelta , date
2
3 # 获取当前时间
4 now = datetime .now ()
5 today = date. today ()
6
7 # 格式化输出
8 formatted = now. strftime ("%Y-%m-%d %H:%M:%S")
9 print ( formatted ) # 2024 -01 -15 10:30:45
10
11 # 解析时间字符串
12 dt = datetime . strptime ("2024 -01 -15", "%Y-%m-%d")
13
14 # 时间计算
15 tomorrow = now + timedelta (days =1)
16 last_week = now - timedelta ( weeks =1)
17
18 # 时间差
19 diff = datetime (2024 , 12, 31) - now
20 print (f" 距 离 年 底 还 有 {[Link]} 天 ")
学习笔记
Python 编程基础学习笔记 18
11 总结与学习建议
11.1 Python 学习路线
1. 基础阶段
• 掌握基本语法和数据类型
• 熟悉控制流和函数
• 理解面向对象编程
2. 进阶阶段
• 深入学习标准库
• 掌握文件操作和异常处理
• 学习装饰器、生成器等高级特性
3. 应用阶段
• 选择感兴趣的方向深入
• Web 开发、数据分析、机器学习等
• 参与实际项目实践
11.2 学习资源推荐
推荐资源
• 官方文档: [Link]
• 在线练习: LeetCode, HackerRank
• 开源项目: GitHub 上的 Python 项目
• 社区论坛: Stack Overflow, 知乎
11.3 编程最佳实践
1. 遵循 PEP 8 编码规范
2. 编写清晰的文档字符串
3. 使用有意义的变量和函数名
4. 保持函数简短,单一职责
5. 编写单元测试
6. 使用版本控制(Git)
7. 持续学习和实践
学习笔记
Python 编程基础学习笔记 19
“编程是思考的过程,代码只是思考的结果。”
学习笔记