Python 知识点总结 – 基础篇
一、Python 基础
1.1 Python 简介
- 定义:Python 是一种高级、解释型、面向对象的编程语言,由 Guido van Rossum 于 1991 年发布。
- 命名由来:名字来源于英国喜剧团体 Monty Python,并非以蛇命名。
- 设计哲学:“优雅”、“明确”、“简单”,强调代码可读性。
- 应用领域:Web 开发、数据科学、人工智能、自动化运维、游戏开发等。
1.2 Python 的特点
- 简单易学:语法简洁,接近自然语言,入门门槛低。
- 跨平台:可在 Windows、Linux、macOS 等多种操作系统上运行。
- 丰富的标准库:内置大量模块,覆盖文件处理、网络通信、正则表达式等功能。
- 强大的第三方库:NumPy、Pandas、TensorFlow、PyTorch 等库支撑科学计算和人工智能。
- 多范式支持:支持面向对象、函数式、过程式编程。
- 动态类型:变量无需声明类型,运行时自动推断。
- 自动内存管理:通过引用计数和垃圾回收机制自动管理内存。
1.3 开发环境
- Python 解释器:核心执行引擎,运行 .py 文件。
- IDE 推荐:
- PyCharm:功能强大,智能提示和调试支持优秀。
- VS Code:轻量级,插件丰富,适合快速开发。
- Jupyter Notebook:交互式编程,适合数据分析和教学。
- 包管理工具:
- pip:Python 官方包管理工具,用于安装和管理第三方库。
- conda:Anaconda 附带的包管理器,适合数据科学环境。
1.4 基本语法
- 注释:
- 单行注释:以 # 开头,注释内容到行尾。
# 这是一行注释
print("Hello") # 这也是注释- 多行注释:使用 """ 内容 """ 或 ''' 内容 ''',常用于文档说明。
"""
这是多行注释
可以写很多行
""" - 关键字:具有特殊含义的保留字,如 if、else、for、while、def、class 等,不可作为变量名。
- 标识符:
- 由字母、数字、下划线组成。
- 不能以数字开头。
- 区分大小写(name 和 Name 是不同变量)。
- 命名规范:
- 驼峰命名法:camelCase(首字母小写,后续单词首字母大写)、PascalCase(所有单词首字母大写)。
- 蛇形命名法:snake_case(单词之间用下划线连接),Python 官方推荐风格。
1.5 变量与数据类型
- 变量:程序运行过程中可改变的值,用于存储数据。语法:变量名 = 值。name = "Alice"
age = 25 - 数值类型:
- int:整数,如 10、-5、0,支持任意精度。
a = 10
b = –5
c = 1000000000000000000000 # Python 支持大整数- float:浮点数,如 3.14、-2.5、1.0e10。
pi = 3.14159
scientific = 1.5e10 # 科学计数法,等于 15000000000.0- complex:复数,如 3 + 4j、2j。
z = 3 + 4j
real_part = z.real # 获取实部
imag_part = z.imag # 获取虚部 - 字符串:
- 用单引号 '、双引号 " 或三引号 """ 包裹。
- 支持 Unicode 编码,可表示中文等任意字符。
- 不可变序列,即创建后不能修改单个字符。
str1 = 'Hello'
str2 = "World"
str3 = """多行
字符串""" - 布尔值:
- True:表示真(等价于 1)。
- False:表示假(等价于 0)。
is_active = True
is_empty = False - 类型转换:
- int(x):转换为整数。
- float(x):转换为浮点数。
- str(x):转换为字符串。
- bool(x):转换为布尔值(0、空字符串、空容器为 False)。
num_str = "123"
num_int = int(num_str) # 123
num_float = float(num_str) # 123.0
is_true = bool(1) # True
is_false = bool(0) # False
1.6 运算符
- 算术运算符:a = 10
b = 3
print(a + b) # 13,加法
print(a – b) # 7,减法
print(a * b) # 30,乘法
print(a / b) # 3.333…,除法
print(a // b) # 3,整除
print(a % b) # 1,取模
print(a ** b) # 1000,幂运算 - 赋值运算符:x = 5
x += 3 # 等价于 x = x + 3,结果为 8
x -= 2 # 等价于 x = x – 2,结果为 6
x *= 4 # 等价于 x = x * 4,结果为 24
x /= 2 # 等价于 x = x / 2,结果为 12.0 - 比较运算符:a = 10
b = 5
print(a > b) # True
print(a >= b) # True
print(a < b) # False
print(a <= b) # False
print(a == b) # False,判断相等
print(a != b) # True,判断不等 - 逻辑运算符:x = True
y = False
print(x and y) # False,逻辑与
print(x or y) # True,逻辑或
print(not x) # False,逻辑非
二、容器类型
2.1 字符串 (str)
- 特性:有序、不可变序列。
- 索引:从 0 开始,支持负数索引(-1 表示最后一个字符)。s = "Hello"
print(s[0]) # 'H'
print(s[–1]) # 'o' - 切片:str[start:end:step],左闭右开区间。s = "Python"
print(s[1:4]) # 'yth'
print(s[:3]) # 'Pyt',从头开始
print(s[2:]) # 'thon',到末尾
print(s[::2]) # 'Pto',步长为 2
print(s[::–1]) # 'nohtyP',反转字符串 - 常用方法:s = " Hello World! "
print(s.find("World")) # 7,查找子串位置
print(s.index("World")) # 7,查找子串位置,未找到抛出异常
print(s.replace("World", "Python")) # ' Hello Python! '
print(s.split()) # ['Hello', 'World!'],按空白分割
print("-".join(["a", "b", "c"])) # 'a-b-c',连接字符串
print(s.strip()) # 'Hello World!',去除首尾空白
print(s.upper()) # ' HELLO WORLD! '
print(s.lower()) # ' hello world! ' - 格式化方式:name = "Alice"
age = 25# %格式化
print("Hello %s, you are %d years old." % (name, age))# format()
print("Hello {}, you are {} years old.".format(name, age))
print("Hello {1}, you are {0} years old.".format(age, name)) # 指定顺序# f-string(Python 3.6+)
print(f"Hello {name}, you are {age} years old.")
print(f"Next year you'll be {age + 1} years old.")
2.2 列表 (list)
- 特性:有序、可变序列,用 [] 表示。
- 创建:list1 = [1, 2, 3, 4, 5]
list2 = list(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list3 = ["apple", "banana", "cherry"] - 常用方法:fruits = ["apple", "banana", "cherry"]
fruits.append("date") # 添加到末尾:["apple", "banana", "cherry", "date"]
fruits.extend(["fig", "grape"]) # 添加多个元素:["apple", "banana", "cherry", "date", "fig", "grape"]
fruits.insert(1, "blueberry") # 在索引 1 处插入:["apple", "blueberry", "banana", "cherry", "date", "fig", "grape"]
fruits.remove("banana") # 删除第一个匹配项:["apple", "blueberry", "cherry", "date", "fig", "grape"]
removed = fruits.pop() # 删除并返回最后一个元素
fruits.clear() # 清空列表numbers = [3, 1, 4, 1, 5, 9]
numbers.sort() # 原地排序:[1, 1, 3, 4, 5, 9]
numbers.reverse() # 原地反转:[9, 5, 4, 3, 1, 1]
print(numbers.index(4)) # 2,返回元素索引
print(numbers.count(1)) # 2,统计元素出现次数 - 嵌套列表:matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[0][1]) # 2,访问第一行第二列
2.3 元组 (tuple)
- 特性:有序、不可变序列,用 () 表示。
- 创建:t1 = (1, 2, 3)
t2 = 1, 2, 3 # 括号可省略
t3 = (1,) # 单元素元组必须加逗号 - 常用方法:t = (1, 2, 3, 2, 4)
print(t.count(2)) # 2,统计出现次数
print(t.index(3)) # 2,返回索引 - 应用场景:# 函数返回多个值
def get_size():
width = 10
height = 20
return width, height # 实际返回元组w, h = get_size() # 解包
2.4 字典 (dict)
- 特性:无序键值对集合,用 {} 表示(Python 3.7+ 保持插入顺序)。
- 键的要求:必须是不可变类型(字符串、数字、元组)。
- 常用方法:person = {"name": "Alice", "age": 25, "city": "New York"}
print(person.keys()) # dict_keys(['name', 'age', 'city'])
print(person.values()) # dict_values(['Alice', 25, 'New York'])
print(person.items()) # dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])print(person.get("name")) # 'Alice'
print(person.get("gender", "Unknown")) # 'Unknown',键不存在返回默认值person.pop("city") # 删除键并返回值
person.update({"gender": "female", "age": 26}) # 更新字典person.clear() # 清空字典
- 遍历方式:person = {"name": "Alice", "age": 25}
# 遍历键
for key in person:
print(key)# 遍历值
for value in person.values():
print(value)# 遍历键值对
for key, value in person.items():
print(f"{key}: {value}")
2.5 集合 (set)
- 特性:无序、不重复元素集合,用 {} 或 set() 表示。
- 创建:s1 = {1, 2, 3, 3, 2} # 自动去重:{1, 2, 3}
s2 = set([1, 2, 2, 3]) # 从列表创建:{1, 2, 3}
s3 = set() # 空集合 - 常用操作:s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}print(s1 & s2) # {3, 4},交集
print(s1 | s2) # {1, 2, 3, 4, 5, 6},并集
print(s1 – s2) # {1, 2},差集
print(s1 ^ s2) # {1, 2, 5, 6},对称差 - 常用方法:s = {1, 2, 3}
s.add(4) # 添加元素:{1, 2, 3, 4}
s.remove(2) # 删除元素,不存在抛出异常
s.discard(5) # 删除元素,不存在不报错
s.clear() # 清空集合 - 应用场景:# 去重
duplicates = [1, 2, 2, 3, 3, 3]
unique = list(set(duplicates)) # [1, 2, 3]
三、控制流程
3.1 条件语句
- 单分支:age = 18
if age >= 18:
print("成年人") - 双分支:score = 85
if score >= 60:
print("及格")
else:
print("不及格") - 多分支:score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
elif score >= 60:
print("及格")
else:
print("不及格") - 三元运算符:age = 20
status = "成年" if age >= 18 else "未成年"
print(status) # '成年' - 注意:Python 使用缩进(通常 4 个空格)表示代码块,而非大括号。
3.2 循环语句
- while 循环:count = 0
while count < 5:
print(count)
count += 1 # 必须修改条件,否则无限循环
# 输出:0 1 2 3 4 - for 循环:fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 输出:apple banana cherry - range() 函数:for i in range(5):
print(i) # 0 1 2 3 4for i in range(2, 8):
print(i) # 2 3 4 5 6 7for i in range(0, 10, 2):
print(i) # 0 2 4 6 8 - 嵌套循环:for i in range(3):
for j in range(3):
print(f"({i}, {j})", end=" ")
print()
# 输出:
# (0, 0) (0, 1) (0, 2)
# (1, 0) (1, 1) (1, 2)
# (2, 0) (2, 1) (2, 2)
3.3 跳转语句
- break:for i in range(10):
if i == 5:
break # 终止循环
print(i)
# 输出:0 1 2 3 4 - continue:for i in range(10):
if i % 2 == 0:
continue # 跳过偶数
print(i)
# 输出:1 3 5 7 9 - else 子句:for i in range(5):
if i == 10:
break
else:
print("循环正常结束") # 会执行,因为没有 breakfor i in range(5):
if i == 3:
break
else:
print("循环正常结束") # 不会执行,因为被 break 终止
四、函数
4.1 函数定义与调用
- 定义语法:def greet(name):
"""向用户打招呼"""
print(f"Hello, {name}!")# 调用
greet("Alice") # 输出:Hello, Alice! - 带返回值的函数:def add(a, b):
"""计算两个数的和"""
return a + bresult = add(3, 5)
print(result) # 8
4.2 参数类型
- 位置参数:def power(base, exponent):
return base ** exponentresult = power(2, 3) # base=2, exponent=3
print(result) # 8 - 关键字参数:result = power(exponent=3, base=2) # 顺序无关
print(result) # 8 - 默认参数:def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"print(greet("Alice")) # "Hello, Alice!"
print(greet("Bob", "Hi")) # "Hi, Bob!" - 可变参数:# *args:接收任意数量的位置参数
def sum_all(*args):
total = 0
for num in args:
total += num
return totalprint(sum_all(1, 2, 3)) # 6
print(sum_all(1, 2, 3, 4, 5)) # 15# **kwargs:接收任意数量的关键字参数
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")print_info(name="Alice", age=25, city="New York")
4.3 返回值
- 单个返回值:def square(x):
return x ** 2 - 多个返回值:def calculate(a, b):
return a + b, a – b, a * b, a / badd_result, sub_result, mul_result, div_result = calculate(10, 5)
print(add_result) # 15
print(sub_result) # 5
print(mul_result) # 50
print(div_result) # 2.0
4.4 匿名函数
- 语法:lambda 参数: 表达式
- 示例:add = lambda x, y: x + y
print(add(3, 5)) # 8# 作为高阶函数参数
numbers = [(1, 3), (2, 1), (3, 2)]
sorted_numbers = sorted(numbers, key=lambda x: x[1])
print(sorted_numbers) # [(2, 1), (3, 2), (1, 3)]
4.5 函数嵌套
- 定义:函数内部定义另一个函数
- 示例:def outer_function(x):
def inner_function(y):
return y * 2result = inner_function(x)
return result + 1print(outer_function(5)) # 11
- 闭包:内部函数可以访问外部函数的变量def make_adder(n):
def adder(x):
return x + n
return adderadd5 = make_adder(5)
print(add5(3)) # 8
print(add5(10)) # 15



