目录
第一章:环境搭建
1.1 安装Python
- 安装时勾选"Add Python to PATH"
- 验证安装:打开终端输入
python --version
1.2 开发工具推荐
- Jupyter Notebook:适合数据分析和学习
1.3 第一个程序
print(
"Hello, World!")
第二章:基础语法
2.1 注释
# 这是单行注释
"""
这是多行注释
可以写多行
"""
2.2 变量
name = "小明" # 字符串
age = 12 # 整数
height = 1.65 # 浮点数
is_student = True # 布尔值
2.3 输入输出
# 输入
name = input("请输入你的名字:")
age = int(input("请输入你的年龄:"))
# 输出
print("你好," + name + "!")
print(f"你今年{age}岁了") # f-string格式化
2.4 命名规则
第三章:数据类型
3.1 数字类型
# 整数
a = 100
b = -50
# 浮点数
pi = 3.14159
c = 2.5e10 # 科学计数法
# 复数
d = 3 + 4j
3.2 布尔类型
x = True
y = False
# 布尔运算
print(3 > 2) # True
print(3 2) # False
print(3 == 3) # True
print(3
!= 3) # False
3.3 类型转换
# int() 转整数
a = int("123") # 123
b = int(3.14) # 3
# float() 转浮点数
c = float("3.14") # 3.14
d = float(100) # 100.0
# str() 转字符串
e = str(123) # "123"
f = str(3.14) # "3.14"
# bool() 转布尔
print(bool(1)) # True
print(bool(0)) # False
print(bool("")) # False
3.4 类型检查
x = 100
print(type(x)) #
第四章:运算符
4.1 算术运算符
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 幂运算
4.2 比较运算符
x = 10
y = 20
print(x > y) # False
print(x < y) # True
print(x >= 10) # True
print(x <= 10) # True
print(x == y) # False
print(x != y) # True
4.3 逻辑运算符
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
4.4 赋值运算符
a = 10
a += 5 # a = a + 5 = 15
a -= 3 # a = a - 3 = 12
a *= 2 # a = a * 2 = 24
a /= 4 # a = a / 4 = 6.0
a //= 2 # a = a // 2 = 3.0
a %= 2 # a = a % 2 = 1.0
第五章:条件判断
5.1 if语句
score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
elif score >= 70:
print("中等")
elif score >= 60:
print("及格")
else:
print("不及格")
5.2 嵌套if
age = 25
has_id = True
if
age >= 18:
if has_id:
print("可以进入")
else:
print("请出示身份证")
else:
print("未成年不能进入")
5.3 三元表达式
x = 10
result = "正数" if x > 0 else "非正数"
print(result) # 正数
5.4 match-case(Python 3.10+)
command = "start"
match command:
case "start":
print("启动程序")
case "stop":
print("停止程序")
case _:
print("未知命令")
第六章:循环结构
6.1 for循环
# 遍历列表
fruits = ["苹果", "香蕉", "橘子"]
for fruit in fruits:
print(fruit)
# 使用range()
for i in range(1, 6):
print(i) # 1 2 3 4 5
# 带步长的range
for i in range(0, 10, 2):
print(i) # 0 2 4 6 8
6.2 while循环
count = 1
while count <= 5:
print(count)
count += 1
6.3 break和continue
# break 跳出循环
for i in range(1, 11):
if i == 5:
break
print(i) # 1 2 3 4
# continue 跳过当前循环
for i in range(1, 11):
if i % 2 == 0:
continue
print(i)
# 1 3 5 7 9
6.4 循环与else
for i in range(5):
if i == 10:
break
else:
print("循环正常结束") # 会执行,因为没有break
第七章:函数
7.1 函数定义与调用
def greet(name):
print(f"你好,{name}!")
greet("小明") # 你好,小明!
7.2 返回值
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 8
7.3 默认参数
def greet(name, greeting="你好"):
print(f"{greeting},{name}!")
greet("小明") # 你好,小明!
greet("小明", "早上好") # 早上好,小明!
7.4 可变参数
# *args 接收任意数量的位置参数
def add_all(*numbers):
return sum(numbers)
print(add_all(1, 2, 3, 4)) # 10
# **kwargs 接收任意数量的关键字参数
def print_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_info(name="小明", age=12)
7.5 Lambda函数
add = lambda a, b: a + b
print(add(3, 5))
# 8
# 常用于排序
students = [("小明", 85), ("小红", 92), ("小刚", 78)]
students.sort(key=lambda x: x[1], reverse=True)
print(students) # [('小红', 92), ('小明', 85), ('小刚', 78)]
7.6 作用域
x = 10 # 全局变量
def func():
x = 20# 局部变量
print(x) # 20
func()
print(x) # 10
# 使用global修改全局变量
def func2():
global x
x = 30
func2()
print(x) # 30
第八章:数据结构
8.1 列表(List)
# 创建列表
fruits = ["苹果", "香蕉", "橘子"]
numbers = [1, 2, 3, 4, 5]
# 访问元素
print(fruits[0]) # 苹果
print(fruits[-1]) # 橘子
# 切片
print(numbers[1:3]) # [2, 3]
print(numbers[:3]) # [1, 2, 3]
print(numbers[2:]) # [3, 4, 5]
# 常用方法
fruits.append("葡萄") # 添加元素
fruits.insert(1, "西瓜") # 插入元素
fruits.remove("香蕉") # 删除元素
fruits.pop() # 删除最后一个
fruits.sort() # 排序
fruits.reverse() # 反转
fruits.index("苹果") # 查找索引
fruits.count("苹果") # 统计个数
len(fruits) # 长度
8.2 元组(Tuple)
# 创建元组
colors = ("红", "绿", "蓝")
# 访问元素
print(colors[0]) # 红
# 元组不可修改
# colors[0] = "黄" # 报错
# 解包
a, b, c = colors
print(a, b, c) # 红 绿 蓝
8.3 字典(Dictionary)
# 创建字典
student = {
"name": "小明",
"age": 12,
"score": 85
}
# 访问元素
print(student["name"]) # 小明
print(student.get("age")) # 12
# 修改/添加元素
student["age"] = 13
student["gender"] = "男"
# 删除元素
del student["score"]
student.pop("gender")
# 遍历字典
for key, value in student.items():
print(f"{key}: {value}")
# 获取所有键/值
print(student.keys())
print(student.values())
8.4 集合(Set)
# 创建集合
fruits = {"苹果", "香蕉", "橘子"}
# 添加元素
fruits.add("葡萄")
# 删除元素
fruits.remove("香蕉")
# 集合运算
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1 | set2) # 并集 {1, 2, 3, 4}
print(set1 & set2) # 交集 {2, 3}
print(set1 - set2) # 差集 {1}
第九章:字符串操作
9.1 字符串基础
s = "Hello, World!"
print(len(s)) # 13
print(s[0]) # H
print(s[-1]) # !
print(s[0:5]) # Hello
9.2 常用方法
s = " Hello, World! "
print(s.strip()) # "Hello, World!" 去除空格
print(s.lower()) # " hello, world! " 转小写
print(s.upper()) # " HELLO, WORLD! " 转大写
print(s.replace("H", "J")) # " Jello, World! " 替换
print(s.split(",")) # [' Hello', ' World! '] 分割
print(s.find("World")) # 9 查找位置
print(s.count("l")) # 3 统计个数
9.3 字符串格式化
name = "小明"
age = 12
# 方法1:f-string(推荐)
print(f"我叫{name},今年{age}岁")
# 方法2:format
print("我叫{},今年{}岁".format(name, age))
# 方法3:%格式化
print("我叫%s,今年%d岁" % (name, age))
9.4 字符串判断
s = "Hello123"
print(s.isalpha()) # False 是否全是字母
print(s.isdigit()) # False 是否全是数字
print(s.isalnum()) # True 是否全是字母或数字
print(s.isspace()) # False 是否全是空格
第十章:文件操作
10.1 读写文件
# 写入文件
with open(
"test.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!\n")
f.write("第二行\n")
# 读取文件
with open("test.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
10.2 文件模式
# "r" 只读(默认)
# "w" 写入(覆盖)
# "a" 追加
# "r+" 读写
# "wb" 二进制写入
# "rb" 二进制读取
10.3 逐行读取
with open("test.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())
10.4 读取到列表
with open("test.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
print(lines)
10.5 文件操作实战:成绩管理
# 写入成绩
def save_scores(scores):
with open("scores.txt", "w", encoding="utf-8") as f:
for name, score in scores.items():
f.write(f"{name},{score}\n")
# 读取成绩
def load_scores():
scores = {}
with open("scores.txt", "r", encoding="utf-8") as f:
for line in f:
name, score = line.strip().split(",")
scores[name] = int(score)
return scores
# 使用
scores = {"小明": 85, "小红": 92, "小刚": 78}
save_scores(scores)
loaded_scores = load_scores()
print(loaded_scores)
第十一章:异常处理
11.1 try-except
try:
num = int(input("请输入数字:"))
result = 10 / num
print(f"结果:{result}")
except ValueError:
print("输入的不是数字")
except ZeroDivisionError:
print("不能除以零")
except Exception as e:
print(f"发生错误:{e}")
11.2 try-except-else-finally
try:
num = int(input("请输入数字:"))
result = 10 / num
except ValueError:
print("输入的不是数字")
except ZeroDivisionError:
print("不能除以零")
else:
print(f"结果:{result}") # 没有异常时执行
finally:
print("程序结束") # 无论如何都执行
11.3 自定义异常
class AgeError(Exception):
def __init__(self, message="年龄必须在0-150之间"):
self.message = message
super().__init__(self.message)
def check_age(age):
if age 0 or age > 150:
raise AgeError()
print(f"年龄:{age}")
try:
check_age(200)
except AgeError as e:
print(e) # 年龄必须在0-150之间
第十二章:模块与包
12.1 导入模块
# 导入整个模块
import math
print(math.pi)
# 导入特定函数
from math import sqrt
print(sqrt(16))
# 导入并起别名
import numpy as np
# 导入所有(不推荐)
from math import *
12.2 常用内置模块
import os # 操作系统相关
import sys # 系统相关
import
datetime # 日期时间
import json # JSON处理
import re # 正则表达式
import random # 随机数
import math # 数学函数
12.3 自定义模块
# mymodule.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
PI = 3.14159
# main.py
import mymodule
print(mymodule.add(3, 5))
print(mymodule.PI)
12.4 包
mypackage/
├── __init__.py
├── module1.py
└── module2.py
from mypackage import module1
from mypackage.module2 import func
第十三章:面向对象编程
13.1 类与对象
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name}在汪汪叫")
def info(self):
print(f"名字:{self.name},年龄:{self.age}岁")
# 创建对象
dog1 = Dog("旺财", 3)
dog1.bark() # 旺财在汪汪叫
dog1.info() # 名字:旺财,年龄:3岁
13.2 继承
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
returnf"{self.name}:汪汪汪!"
class Cat(Animal):
def speak(self):
returnf"{self.name}:喵喵喵!"
dog = Dog("旺财")
cat = Cat("咪咪")
print(dog.speak()) # 旺财:汪汪汪!
print(cat.speak()) # 咪咪:喵喵喵!
13.3 多态
def animal_sound(animal):
print(animal.speak())
animal_sound(Dog("旺财"))
animal_sound(Cat("咪咪"))
13.4 属性装饰器
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value 0:
raise ValueError("半径不能为负")
self._radius = value
@property
def area(self):
return3.14 * self._radius ** 2
c = Circle(5)
print(c.area) # 78.5
c.radius = 10
print(c.area) # 314.0
13.5 特殊方法
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
returnf"Vector({self.x}, {self.y})"
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __len__(self):
return int((self.x**2 + self.y**2)**0.5)
v1 = Vector(3, 4)
v2 = Vector(1, 2)
print(v1) # Vector(3, 4)
print(v1 + v2) # Vector(4, 6)
print(len(v1)) # 5
第十四章:迭代器与生成器
14.1 迭代器
nums = [1, 2, 3]
it = iter(nums)
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3
14.2 生成器
def countdown(n):
while n > 0:
yield n
n -= 1
for i in countdown(5):
print(i) # 5 4 3 2 1
14.3 生成器表达式
# 列表推导式(占用内存)
squares_list = [x**2 for x in range(1000000)]
# 生成器表达式(节省内存)
squares_gen = (x**
2 for x in range(1000000))
print(next(squares_gen)) # 0
print(next(squares_gen)) # 1
14.4 实战:读取大文件
def read_large_file(file_path):
with open(file_path, 'r') as f:
for line in f:
yield line.strip()
# 不会一次性加载整个文件到内存
for line in read_large_file("large_file.txt"):
process(line)
第十五章:装饰器
15.1 函数装饰器
def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__}
执行时间:{end - start:.2f}秒")
return result
return wrapper
@timer
def slow_function():
import time
time.sleep(1)
print("函数执行完毕")
slow_function()
15.2 带参数的装饰器
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(times=3)
def greet(name):
print(f"你好,{name}!")
greet("小明")
15.3 类装饰器
class Timer:
def __init__(self, func):
self.func = func
def
__call__(self, *args, **kwargs):
import time
start = time.time()
result = self.func(*args, **kwargs)
end = time.time()
print(f"执行时间:{end - start:.2f}秒")
return result
@Timer
def slow_function():
import time
time.sleep(1)
slow_function()
第十六章:正则表达式
16.1 基础用法
import re
# 查找
text = "我的电话是13812345678,邮箱是test@example.com"
phone = re.search(r'1[3-9]\d{9}', text)
if phone:
print(f"找到电话:{phone.group()}")
# 匹配所有
emails = re.findall(r'[\w.]+@[\w.]+', text)
print(emails)
16.2 常用模式
import re
# 常用元字符
# \d 数字
# \w 字母数字下划线
# \s 空白字符
# . 任意字符
# * 0次或多次
# + 1次或多次
# ? 0次或1次
# {n} 恰好n次
# {n,m} n到m次
# ^ 开始
# $ 结束
# 示例
text = "2024-01-15"
date = re.match(r'(\d{4})-(\d{2})-(\d{2})', text)
if date:
year, month, day = date.groups()
print(f"年:{year},月:{month},日:{day}")
16.3 替换与分割
import re
# 替换
text = "电话:138-1234-5678"
cleaned = re.sub(r'-', '', text)
print(cleaned) # 电话:13812345678
# 分割
text = "苹果,香蕉 橘子;葡萄"
parts = re.split(r'[,;\s]+', text)
print(parts) # ['苹果', '香蕉', '橘子', '葡萄']
第十七章:多线程与多进程
17.1 多线程
import threading
import time
def worker(name):
print(f"线程{name}开始")
time.sleep(1)
print(f"线程{name}结束")
# 创建线程
t1 = threading.Thread(target=worker, args=("A",))
t2 = threading.Thread(target=worker, args=("B",))
# 启动线程
t1.start()
t2.start()
# 等待线程结束
t1.join()
t2.join()
print("所有线程完成")
17.2 线程安全
import threading
counter = 0
lock = threading.Lock()
def increment():
global counter
for _ in range(100000):
lock.acquire()
counter += 1
lock.release()
threads = [threading.Thread(target=increment) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
print(counter) # 500000
17.3 多进程
from multiprocessing import
Process
import os
def worker():
print(f"进程{os.getpid()}开始")
if __name__ == "__main__":
processes = [Process(target=worker) for _ in range(3)]
for p in processes:
p.start()
for p in processes:
p.join()
第十八章:网络编程
18.1 TCP客户端
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("www.example.com", 80))
client.send(b"GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n")
response = client.recv(1024)
print(response.decode())
client.close()
18.2 TCP服务器
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 8888))
server.listen(5
)
print("服务器启动,等待连接...")
while True:
client, addr = server.accept()
print(f"连接来自:{addr}")
data = client.recv(1024)
client.send(data)
client.close()
18.3 HTTP请求
import requests
# GET请求
response = requests.get("https://api.github.com")
print(response.json())
# POST请求
data = {"username": "test", "password": "123456"}
response = requests.post("https://httpbin.org/post", data=data)
print(response.json())
第十九章:数据库操作
19.1 SQLite
import sqlite3
# 连接数据库
conn = sqlite3.connect("test.db")
cursor = conn.cursor()
# 创建表
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)
""")
# 插入数据
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("小明", 12))
conn.commit()
# 查询数据
cursor.execute("SELECT * FROM users")
users = cursor.fetchall()
for user in users:
print(user)
# 关闭连接
conn.close()
19.2 MySQL
import pymysql
# 连接数据库
conn = pymysql.connect(
host="localhost",
user="root",
password="password",
database="test"
)
cursor = conn.cursor()
# 执行SQL
cursor.execute("SELECT * FROM users")
users = cursor.fetchall()
for user in users:
print(user)
conn.close()
19.3 ORM:SQLAlchemy
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
engine = create_engine('sqlite:///test.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# 添加用户
new_user = User(name="小明", age=12)
session.add(new_user)
session.commit()
# 查询用户
users = session.query(User).all()
for user in users:
print(user.name, user.age)
第二十章:实战项目
20.1 待办事项管理
import json
TODO_FILE = "todos.json"
def load_todos():
try:
with open(TODO_FILE, 'r') as f:
return json.load(f)
except FileNotFoundError:
return []
def save_todos(todos):
with open(TODO_FILE, 'w') as f:
json.dump(todos, f, ensure_ascii=False, indent=2)
def add_todo(title):
todos = load_todos()
todos.append({"title": title, "done": False})
save_todos(todos)
print(f"已添加:{title}")
def complete_todo(index):
todos = load_todos()
if0 <= index < len(todos):
todos[index]["done"] = True
save_todos(todos)
print(f"已完成:{todos[index]['title']}")
def show_todos():
todos = load_todos()
ifnot todos:
print("暂无待办事项")
return
for i, todo in enumerate(todos):
status = "✓"if todo["done"] else" "
print(f"{i}. [{status}] {todo['title']}")
def main():
whileTrue:
print("\n1. 添加待办")
print("2. 完成待办")
print("3. 查看待办")
print("4. 退出")
choice = input("请选择:")
if choice == "1":
title = input("输入待办内容:")
add_todo(title)
elif choice == "2":
index = int(input("输入待办编号:"))
complete_todo(index)
elif choice == "3":
show_todos()
elif choice == "4":
break
if __name__ == "__main__":
main()
20.2 简易计算器
def calculator():
whileTrue:
print("\n1. 加法")
print("2. 减法")
print("3. 乘法")
print("4. 除法")
print("5. 退出")
choice = input("请选择运算:")
if choice == "5":
break
if choice in ("1", "2", "3", "4"):
a = float(input("输入第一个数:"))
b = float(input("输入第二个数:"))
if choice == "1":
print(f"结果:{a + b}")
elif choice == "2":
print(f"结果:{a - b}")
elif choice == "3":
print(f"结果:{a * b}")
elif choice == "4":
if b != 0:
print(f"结果:{a / b}")
else:
print("错误:除数不能为0")
else:
print("无效选择")
if __name__ == "__main__":
calculator()
20.3 批量文件重命名
import os
def batch_rename(folder_path, old_str, new_str):
for filename in os.listdir(folder_path):
if old_str in filename:
new_filename = filename.replace(old_str, new_str)
old_path = os.path.join(folder_path, filename)
new_path = os.path.join(folder_path, new_filename)
os.rename(old_path, new_path)
print(f"重命名:{filename} -> {new_filename}")
# 使用示例
# batch_rename("D:/photos", "IMG_", "照片_")
20.4 简易爬虫
import requests
from bs4 import BeautifulSoup
def scrape_title(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
return soup.title.string
def scrape_links(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
links = []
for link in soup.find_all('a', href=True):
links.append(link['href'])
return links
# 使用示例
# title = scrape_title("https://www.example.com")
# print(title)
20.5 数据可视化
import matplotlib.pyplot as plt
# 折线图
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y, marker='o')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.title('折线图')
plt.savefig('line_chart.png')
plt.show()
# 柱状图
categories = ['A', 'B', 'C', 'D']
values = [15, 30, 45, 20]
plt.bar(categories, values)
plt.title('柱状图')
plt.savefig('bar_chart.png')
plt.show()
# 饼图
sizes = [30, 25, 20, 25]
labels = ['A',
'B', 'C', 'D']
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title('饼图')
plt.savefig('pie_chart.png')
plt.show()
附录:Python常用内置函数
# 数学函数
abs(-5) # 5 绝对值
max(1, 2, 3) # 3 最大值
min(1, 2, 3) # 1 最小值
sum([1, 2, 3]) # 6 求和
round(3.14, 1) # 3.1 四舍五入
# 序列函数
len([1, 2, 3]) # 3 长度
sorted([3, 1, 2]) # [1, 2, 3] 排序
enumerate(['a', 'b']) # [(0, 'a'), (1, 'b')] 枚举
zip([1, 2], [
'a', 'b']) # [(1, 'a'), (2, 'b')] 打包
# 类型转换
int("123") # 123
float("3.14") # 3.14
str(123) # "123"
list("abc") # ['a', 'b', 'c']
dict([("a", 1), ("b", 2)]) # {'a': 1, 'b': 2}
# 其他
type(123) #
isinstance(123, int) # True
id([1, 2, 3]) # 对象唯一标识
hash("hello") # 哈希值
结语
恭喜你完成了Python完整教程的学习!这份教程涵盖了Python从入门到进阶的所有核心知识点。记住:
- 善用文档和社区 - Python官方文档是最好的学习资源
祝你编程之路越走越远!