Python 编程

简单易学、功能强大的编程语言


第一章 Python简介与环境配置

1.1 Python概述

Python是一种高级、解释型、面向对象的编程语言。由Guido van Rossum于1991年首次发布,目前由Python Software Foundation维护。

Python这个名字来源于Guido喜欢的喜剧团体Monty Python,而不是蛇。

1.1.1 Python的哲学

Python的设计哲学强调代码的可读性和简洁的语法。Python开发者遵循"Python之禅":

The Zen of Python

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

1.1.2 Python的特点

  1. 简单易学:Python语法简洁,接近自然语言
  2. 面向对象:支持面向对象编程
  3. 解释型:无需编译,直接运行
  4. 跨平台:Windows、Mac、Linux都能运行
  5. 丰富的库:标准库和第三方库非常丰富
  6. 动态类型:不需要声明变量类型
  7. 自动内存管理:不需要手动管理内存

1.1.3 Python的应用领域

  • Web开发:Django、Flask、FasterAPI
  • 数据分析:Pandas、NumPy、Matplotlib
  • 人工智能:TensorFlow、PyTorch、Scikit-learn
  • 自动化脚本:网络爬虫、自动化测试
  • 科学计算:SciPy、Biopython
  • 游戏开发:Pygame、Panda3D
  • 网络编程:Socket、Twisted
  • GUI开发:Tkinter、PyQt、wxPython

1.2 Python版本

1.2.1 Python 2 vs Python 3

Python 2于2000年发布,Python 3于2008年发布。Python 2已于2020年停止维护,推荐使用Python 3。

主要区别:
- print函数:print "hello" vs print("hello")
- 整数除法:1/2=0 vs 1/2=0.5
- 字符串编码:Unicode支持
- 异常语法:except Exception, e vs except Exception as e

1.2.2 Python 3.10+ 新特性

  • 模式匹配(match/case)
  • 更好的错误信息
  • 性能改进

1.3 环境配置

1.3.1 安装Python

Windows安装
1. 访问 python.org/downloads
2. 下载最新版本
3. 运行安装程序
4. 勾选"Add Python to PATH"
5. 点击Install Now

macOS安装

# 使用Homebrew
brew install python3

# 或下载官方安装包

Linux安装

# Ubuntu/Debian
sudo apt update
sudo apt install python3

# CentOS/RHEL
sudo yum install python3

# Fedora
sudo dnf install python3

1.3.2 验证安装

python3 --version
python --version  # 指向Python 3

1.3.3 pip包管理器

pip是Python的包管理工具。

# 升级pip
python -m pip install --upgrade pip

# 安装包
pip install package_name
pip install package==1.0.0
pip install package>=1.0.0

# 卸载包
pip uninstall package_name

# 查看已安装的包
pip list
pip freeze

# 导出依赖
pip freeze > requirements.txt

# 从文件安装
pip install -r requirements.txt

1.3.4 虚拟环境

虚拟环境用于隔离项目的依赖。

# 使用venv(Python 3.3+内置)
python3 -m venv myenv

# 激活虚拟环境
# Linux/macOS
source myenv/bin/activate
# Windows
myenv\Scriptsctivate

# 退出虚拟环境
deactivate

# 使用virtualenv(第三方)
pip install virtualenv
virtualenv myenv

# 使用pipenv(高级)
pip install pipenv
pipenv install
pipenv shell

# 使用poetry(现代方式)
pip install poetry
poetry init
poetry add package

1.4 开发工具

1.4.1 代码编辑器

  • VS Code:免费,功能强大,插件丰富
  • PyCharm:专业,智能提示,适合大型项目
  • Sublime Text:轻量,快速
  • Atom:免费,开源
  • Jupyter Notebook:数据分析、机器学习

1.4.2 IDE配置

VS Code配置Python
1. 安装Python扩展
2. 安装Pylance扩展
3. 选择Python解释器

1.4.3 第一个Python程序

# hello.py
print("Hello, World!")

# 运行
python hello.py

第二章 Python基础语法

2.1 变量与数据类型

2.1.1 变量

变量是存储数据的容器。在Python中,变量不需要声明类型,直接赋值即可。

# 变量赋值
x = 10              # 整数
name = "Alice"      # 字符串
is_active = True    # 布尔值
price = 19.99       # 浮点数

# 多个变量赋值
a, b, c = 1, 2, 3
x = y = z = 0      # 三个变量都指向0

# 变量命名规则
# - 必须以字母或下划线开头
# - 可以包含字母、数字、下划线
# - 区分大小写
# - 不能使用Python关键字

# 合法变量名
user_name
UserName
_private
PI
CONSTANT_VALUE

# 非法变量名
# 2name
# my-name
# class

2.1.2 基本数据类型

Python中有多种内置数据类型:

整数(int)

age = 25
count = 1000000
negative = -42
hex_num = 0xFF        # 十六进制 255
binary_num = 0b1010   # 二进制 10
octal_num = 0o755     # 八进制 493

# 大整数支持
big_num = 10**100     # 很大的数

浮点数(float)

price = 19.99
pi = 3.14159
scientific = 1.5e10   # 1.5 × 10^10

字符串(str)

# 单引号
name = 'Alice'

# 双引号
message = "Hello, World!"

# 三引号(多行字符串)
poem = """春眠不觉晓,
处处闻啼鸟。
夜来风雨声,
花落知多少。"""

# 转义字符
path = "C:\Users\Admin\file.txt"
new_line = "第一行
第二行"
tabbed = "列1    列2"

布尔值(bool)

is_active = True
is_deleted = False

# 布尔运算
and_result = True and False   # False
or_result = True or False    # True
not_result = not True        # False

复数(complex)

complex_num = 3 + 4j
real_part = complex_num.real  # 3.0
imag_part = complex_num.imag  # 4.0

2.1.3 类型转换

# 转换为整数
int(3.7)        # 3
int("42")        # 42
int("1010", 2)   # 10(二进制)

# 转换为浮点数
float(10)        # 10.0
float("3.14")    # 3.14

# 转换为字符串
str(123)         # "123"
str([1, 2, 3])   # "[1, 2, 3]"

# 转换为布尔值
bool(1)          # True
bool(0)          # False
bool("")         # False
bool("any")      # True

2.1.4 类型检查

x = 10
type(x)                  # <class 'int'>
isinstance(x, int)      # True
isinstance(x, (int, float))  # True

2.2 运算符

2.2.1 算术运算符

a, b = 10, 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

2.2.2 比较运算符

a, b = 10, 20

==   # 等于
!=   # 不等于
>    # 大于
<    # 小于
>=   # 大于等于
<=   # 小于等于

print(a == b)  # False
print(a != b)  # True
print(a > b)   # False
print(a < b)   # True

# 链式比较
1 < 2 < 3      # True
1 < 2 > 3      # False

2.2.3 逻辑运算符

# and:两者都为True才为True
True and True    # True
True and False   # False
False and False  # False

# or:任一为True就为True
True or False    # True
False or False   # False

# not:取反
not True         # False
not False        # True

# 短路求值
# and:如果第一个为False,直接返回第一个值
# or:如果第一个为True,直接返回第一个值

2.2.4 位运算符

a, b = 5, 2   # 5=101, 2=010

&    # 按位与
|    # 按位或
^    # 按位异或
~    # 按位取反
<<   # 左移
>>   #右移

print(a & b)   # 0 (000)
print(a | b)   # 7 (111)
print(a ^ b)   # 7 (111)
print(~a)      # -6
print(a << 1)  # 10 (1010)
print(a >> 1)  # 2 (10)

2.2.5 赋值运算符

x = 10
x += 5    # x = x + 5 = 15
x -= 3    # x = x - 3 = 12
x *= 2    # x = x * 2 = 24
x /= 4    # x = x / 4 = 6.0
x //= 3   # x = x // 3 = 2.0
x %= 3    # x = x % 3 = 2.0
x **= 2   # x = x ** 2 = 4.0

2.2.6 身份运算符

# is:检查两个对象是否是同一个对象
a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a is b)   # True(同一个对象)
print(a is c)   # False(不同对象,但内容相同)
print(a == c)   # True(内容相同)

# is not
print(a is not c)  # True

2.2.7 成员运算符

# in:检查是否在序列中
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)     # True
print("grape" in fruits)    # False

# 字符串
name = "Alice"
print("A" in name)    # True
print("z" in name)    # False

# 字典(检查键)
person = {"name": "Alice", "age": 30}
print("name" in person)     # True
print("Alice" in person)    # False(检查键,不是值)

2.3 控制流

2.3.1 条件语句

# if-elif-else
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"成绩等级: {grade}")

# 简化的条件表达式(三元运算符)
age = 20
status = "成人" if age >= 18 else "未成年"
print(status)

# 多条件
is_student = True
is_member = False

if is_student or is_member:
    print("享受折扣")

# 嵌套条件
x = 10
if x > 0:
    if x % 2 == 0:
        print("正偶数")
    else:
        print("正奇数")
else:
    print("非正数")

2.3.2 循环

for循环

# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# 遍历字符串
for char in "hello":
    print(char)

# 使用range
for i in range(5):          # 0,1,2,3,4
    print(i)

for i in range(1, 6):       # 1,2,3,4,5
    print(i)

for i in range(0, 10, 2):   # 0,2,4,6,8(步长为2)
    print(i)

# 遍历字典
person = {"name": "Alice", "age": 30, "city": "Beijing"}
for key in person:
    print(f"{key}: {person[key]}")

for key, value in person.items():
    print(f"{key}: {value}")

for value in person.values():
    print(value)

# 枚举(带索引)
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits, start=1):
    print(f"{index}. {fruit}")

while循环

# 基本while循环
count = 0
while count < 5:
    print(count)
    count += 1

# while-else
count = 0
while count < 3:
    print(count)
    count += 1
else:
    print("循环正常结束")

# break:跳出循环
for i in range(10):
    if i == 5:
        break
    print(i)

# continue:跳过本次循环
for i in range(5):
    if i == 2:
        continue
    print(i)  # 0,1,3,4(跳过2)

# pass:占位符(什么都不做)
for i in range(5):
    pass  # 暂时不执行任何操作

循环技巧

# 列表推导式
squares = [x**2 for x in range(10)]
print(squares)  # [0,1,4,9,16,25,36,49,64,81]

# 带条件的列表推导式
evens = [x for x in range(10) if x % 2 == 0]
print(evens)  # [0,2,4,6,8]

# 嵌套列表推导式
matrix = [[i*j for j in range(3)] for i in range(3)]
print(matrix)  # [[0,0,0],[0,1,2],[0,2,4]]

# zip:同时遍历多个序列
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name}: {age}")

第三章 数据结构

3.1 列表(List)

列表是Python中最常用的数据结构之一,可以存储有序的元素集合。

3.1.1 创建列表

# 空列表
empty_list = []
empty_list = list()

# 创建列表
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", True, 3.14, [1, 2]]

# 使用list()转换
string_to_list = list("hello")  # ['h','e','l','l','o']
tuple_to_list = list((1, 2, 3))  # [1, 2, 3]

# 使用range创建
range_list = list(range(10))  # [0,1,2,3,4,5,6,7,8,9]

3.1.2 访问元素

fruits = ["apple", "banana", "cherry", "date", "elderberry"]

# 索引访问(从0开始)
print(fruits[0])   # apple
print(fruits[2])   # cherry

# 负索引(从-1开始)
print(fruits[-1])  # elderberry(最后一个)
print(fruits[-2])   # date(倒数第二个)

# 切片
print(fruits[1:4])    # ['banana','cherry','date']
print(fruits[:3])      # ['apple','banana','cherry']
print(fruits[2:])      # ['cherry','date','elderberry']
print(fruits[::2])     # ['apple','cherry','elderberry'](步长2)
print(fruits[::-1])    # ['elderberry','date','cherry','banana','apple'](反转)

3.1.3 修改列表

fruits = ["apple", "banana", "cherry"]

# 修改元素
fruits[0] = "avocado"
print(fruits)  # ['avocado','banana','cherry']

# 添加元素
fruits.append("date")       # 末尾添加
fruits.insert(1, "apricot") # 指定位置插入
fruits.extend(["elderberry", "fig"])  # 批量添加

# 删除元素
fruits.remove("banana")    # 删除第一个匹配项
popped = fruits.pop()       # 删除并返回最后一个
del fruits[0]               # 删除指定位置
fruits.clear()              # 清空列表

3.1.4 列表方法

numbers = [3, 1, 4, 1, 5, 9, 2, 6]

# 排序
numbers.sort()               # 原地排序
sorted_numbers = sorted(numbers)  # 返回新列表
numbers.sort(reverse=True)   # 降序

# 反转
numbers.reverse()           # 原地反转
reversed_numbers = numbers[::-1]  # 返回新列表

# 计数
count = numbers.count(1)

# 查找索引
index = numbers.index(4)

# 复制
copied = numbers.copy()
copied = list(numbers)
copied = numbers[:]

3.1.5 列表操作

# 连接
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2    # [1,2,3,4,5,6]
list1.extend(list2)        # 修改list1

# 重复
repeated = [1, 2] * 3       # [1,2,1,2,1,2]

# 检查元素
print(1 in [1, 2, 3])       # True
print(5 in [1, 2, 3])       # False

3.2 元组(Tuple)

元组是不可变的列表,创建后不能修改。

3.2.1 创建元组

# 创建元组
empty_tuple = ()
single_tuple = (5,)     # 单元素元组需要逗号
point = (10, 20)
colors = ("red", "green", "blue")

# 使用tuple()转换
string_tuple = tuple("hello")  # ('h','e','l','l','o')
list_tuple = tuple([1, 2, 3])  # (1, 2, 3)

3.2.2 访问元组

point = (10, 20, 30)

print(point[0])   # 10
print(point[-1])  # 30
print(point[1:3]) # (20, 30)

3.2.3 元组操作

# 元组不可变,但可以连接
t1 = (1, 2)
t2 = (3, 4)
t3 = t1 + t2   # (1,2,3,4)

# 重复
t4 = (1, 2) * 3  # (1,2,1,2,1,2)

# 解包
x, y = (10, 20)
a, b, c = (1, 2, 3)

# 交换变量
a, b = b, a

3.2.4 元组方法

point = (10, 20, 10, 30)

print(point.count(10))  # 2
print(point.index(20))  # 1

3.3 集合(Set)

集合是无序且不重复的元素集合。

3.3.1 创建集合

# 创建集合
empty_set = set()
fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 4, 5}

# 从列表创建(去重)
unique_nums = set([1, 2, 2, 3, 3, 3])  # {1, 2, 3}

3.3.2 集合操作

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# 并集
union = set1 | set2          # {1,2,3,4,5,6}
union = set1.union(set2)

# 交集
intersection = set1 & set2   # {3, 4}
intersection = set1.intersection(set2)

# 差集
difference = set1 - set2     # {1, 2}
difference = set1.difference(set2)

# 对称差集(并集-交集)
symmetric = set1 ^ set2      # {1, 2, 5, 6}
symmetric = set1.symmetric_difference(set2)

3.3.3 集合方法

fruits = {"apple", "banana"}

# 添加
fruits.add("cherry")
fruits.update(["date", "elderberry"])

# 删除
fruits.remove("banana")      # 元素不存在会报错
fruits.discard("grape")      # 元素不存在不报错
popped = fruits.pop()         # 随机删除一个

# 清空
fruits.clear()

# 子集和超集
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}

print(set1.issubset(set2))     # True(set1是set2的子集)
print(set2.issuperset(set1))   # True(set2是set1的超集)

3.4 字典(Dictionary)

字典是键值对的无序集合。

3.4.1 创建字典

# 创建字典
empty_dict = {}
person = {"name": "Alice", "age": 30, "city": "Beijing"}

# 使用dict()
dict_from_list = dict([("name", "Alice"), ("age", 30)])

# 字典推导式
squares = {x: x**2 for x in range(5)}  # {0:0, 1:1, 2:4, 3:9, 4:16}

3.4.2 访问字典

person = {"name": "Alice", "age": 30, "city": "Beijing"}

# 访问值
print(person["name"])           # Alice
print(person.get("age"))         # 30
print(person.get("country", "Unknown"))  # Unknown(默认值)

# 修改值
person["age"] = 31
person["country"] = "China"  # 添加新键值对

3.4.3 字典方法

person = {"name": "Alice", "age": 30, "city": "Beijing"}

# 获取所有键/值/项
print(person.keys())    # dict_keys(['name','age','city'])
print(person.values())  # dict_values(['Alice',30,'Beijing'])
print(person.items())   # dict_items([('name','Alice'),...])

# 遍历
for key in person:
    print(f"{key}: {person[key]}")

for key, value in person.items():
    print(f"{key}: {value}")

# 删除
del person["city"]           # 删除指定键值对
age = person.pop("age")      # 删除并返回值
person.clear()               # 清空字典

# 更新
person.update({"age": 31, "country": "China"})

第四章 函数

4.1 函数定义与调用

4.1.1 基本函数

# 定义函数
def greet():
    print("Hello!")

# 调用函数
greet()

# 带参数
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")

# 带返回值
def add(a, b):
    return a + b

result = add(3, 5)  # 8

# 多返回值(实际返回元组)
def divide(a, b):
    quotient = a // b
    remainder = a % b
    return quotient, remainder

q, r = divide(10, 3)  # q=3, r=1

4.1.2 参数类型

# 默认参数
def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Alice")           # Hello, Alice!
greet("Bob", "Hi")      # Hi, Bob!

# 关键字参数
def create_user(name, age, city):
    return {"name": name, "age": age, "city": city}

user = create_user(age=25, name="Alice", city="Beijing")

# 可变参数
def sum_all(*args):
    total = 0
    for num in args:
        total += num
    return total

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=30, city="Beijing")

4.1.3 匿名函数(Lambda)

# 基本语法
square = lambda x: x ** 2
print(square(5))  # 25

# 多参数
add = lambda x, y: x + y
print(add(3, 5))  # 8

# 使用场景
numbers = [1, 2, 3, 4, 5]

# map
squared = list(map(lambda x: x ** 2, numbers))

# filter
evens = list(filter(lambda x: x % 2 == 0, numbers))

# sorted
pairs = [(1, "one"), (3, "three"), (2, "two")]
pairs.sort(key=lambda x: x[0])

4.2 作用域

# 全局变量
global_var = "I am global"

def test():
    # 局部变量
    local_var = "I am local"
    print(global_var)  # 可以访问全局变量
    print(local_var)  # 可以访问局部变量

# print(local_var)  # 错误!无法访问局部变量

# 修改全局变量
counter = 0

def increment():
    global counter
    counter += 1

第五章 面向对象编程

5.1 类与对象

class Person:
    # 类属性
    species = "Human"

    # 初始化方法(构造函数)
    def __init__(self, name, age):
        # 实例属性
        self.name = name
        self.age = age

    # 实例方法
    def greet(self):
        return f"Hello, I'm {self.name}"

    # 魔术方法
    def __str__(self):
        return f"Person({self.name}, {self.age})"

    def __repr__(self):
        return self.__str__()

# 创建对象
person = Person("Alice", 30)
print(person.greet())
print(person)

5.2 继承

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

dog = Dog("Buddy")
print(dog.speak())  # Woof!

第六章 模块与包

6.1 导入模块

# 导入整个模块
import math
print(math.sqrt(16))

# 导入特定内容
from math import pi, sin
print(sin(pi/2))

# 导入并起别名
import numpy as np
import pandas as pd

# 导入所有(不推荐)
from math import *

6.2 标准库

# os - 操作系统接口
import os
os.listdir(".")
os.path.exists("file.txt")
os.mkdir("new_dir")

# json - JSON处理
import json
data = {"name": "Alice", "age": 30}
json_str = json.dumps(data)
parsed = json.loads(json_str)

# datetime - 日期时间
from datetime import datetime, timedelta
now = datetime.now()
future = now + timedelta(days=7)

# re - 正则表达式
import re
pattern = r"\d+"
text = "abc123def456"
matches = re.findall(pattern, text)

# collections - 集合容器
from collections import Counter, defaultdict, deque

第七章 异常处理

7.1 异常捕获

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e:
    print(f"Error: {e}")
else:
    print("No errors occurred")
finally:
    print("Cleanup code")

7.2 抛出异常

def divide(a, b):
    if b == 0:
        raise ValueError("Divisor cannot be zero")
    return a / b

第八章 文件操作

8.1 读写文件

# 读取文件
with open("file.txt", "r", encoding="utf-8") as f:
    content = f.read()
    # 或逐行读取
    # for line in f:
    #     print(line.strip())

# 写入文件
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("Hello, World!")

# 追加写入
with open("log.txt", "a", encoding="utf-8") as f:
    f.write("New entry
")

附录:常用代码片段

A.1 列表操作

# 去重
unique = list(set(original_list))

# 列表推导式
squares = [x**2 for x in range(10)]

# 过滤
filtered = [x for x in list if condition]

# 分组
from itertools import groupby
groups = groupby(list, key=lambda x: x.group)

A.2 字符串操作

# 分割
parts = "a,b,c".split(",")

# 连接
joined = "-".join(["a", "b", "c"])

# 格式化
name = "Alice"
age = 30
f"Name: {name}, Age: {age}"
"Name: {}, Age: {}".format(name, age)

# 去除空白
stripped = "  hello  ".strip()

# 替换
replaced = "hello world".replace("world", "Python")

A.3 字典操作

# 合并字典
merged = {**dict1, **dict2}
dict1.update(dict2)

# 字典推导式
new_dict = {k: v**2 for k, v in old_dict.items()}

# 获取键的最大/最小值
max_key = max(d, key=d.get)

笔记整理:AI助手
更新时间:2026-03-19