⚡ python核心编程 python3基础入门
Python作为一种高级动态编程语言,自1991年首次发布以来,凭借其简洁的语法、强大的标准库和活跃的社区生态,已成为全球最流行的编程语言之一。截至2024年,Python在TIOBE指数中稳居前三,在GitHub年度报告中连续多年蝉联最热门语言榜首。本节将系统梳理python核心编程 python3的基础知识体系,为后续高级开发奠定坚实基础。
〈一〉Python 3.x版本演进与核心特性
Python 3.x系列自2008年发布以来,已历经多个重要版本迭代:
- Python 3.0(2008):引入不兼容变更,如print函数化、整数除法行为调整
- Python 3.5(2015):引入async/await语法,正式确立异步编程模型
- Python 3.6(2016):f-string格式化字符串、__init_subclass__机制、字典有序化
- Python 3.8(2019):海象运算符(:=)、位置参数限定符
- Python 3.10(2021):结构化模式匹配(match-case)、联合类型(X | Y)
- Python 3.11(2022):性能提升最高达60%、精准异常位置信息
- Python 3.12(2023):更快的解释器(VM改进)、类型提示增强、warnings优化
- Python 3.13(2024):引入Zombie Reaping机制优化垃圾回收、更多内置类型泛型支持
当前推荐使用python核心编程 python3的最新稳定版本(截至2025年初为3.13.1),其在性能、类型系统、异步支持等方面均达到企业级应用标准。
〈二〉核心语法要素深度解析
1. 变量与命名规范
Python采用动态类型系统,变量无需声明类型,直接赋值即可:
name = "Python" # 字符串
version = 3.13 # 浮点数(实际为float类型)
count = 42 # 整数(int)
is_active = True # 布尔值
data = None # 空值(NoneType)
命名遵循PEP 8规范:
- 小写字母+下划线:变量、函数、模块(如user_name、process_data)
- 大写字母开头:类名(如HttpClient、DataProcessor)
- 全大写+下划线:常量(如MAX_SIZE、API_BASE_URL)
2. 控制流结构
条件判断语句支持多层嵌套与else-if链式结构:
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"
print(f"成绩等级:{grade}")
循环结构支持for-in遍历任意可迭代对象:
for i in range(5): # 生成0~4的整数序列
print(i, end=" ")
# 输出:0 1 2 3 4
# 嵌套循环生成乘法表
for i in range(1, 10):
for j in range(1, i+1):
print(f"{j}×{i}={i*j:2d}", end=" ")
print()
3. 函数定义与参数传递
函数支持默认参数、可变参数、关键字参数等多种形式:
def calculate(x, y, operation="add"):
"""支持多种运算的函数"""
if operation == "add":
return x + y
elif operation == "sub":
return x - y
elif operation == "mul":
return x * y
elif operation == "div":
return x / y if y != 0 else float('inf')
else:
raise ValueError("不支持的操作类型")
# 使用示例
print(calculate(10, 5)) # 默认加法:15
print(calculate(10, 5, "mul")) # 乘法:50
print(calculate(y=3, x=7)) # 关键字参数:10
支持可变参数与关键字参数:
def log_events(level, *messages, **options):
"""日志记录函数"""
prefix = f"[{level.upper()}]"
for msg in messages:
print(f"{prefix} {msg}")
if options:
print(" 选项:", options)
log_events("INFO", "启动服务", "加载配置", timeout=30, retries=3)
⚙️ 数据结构与算法基础
〈一〉内置数据结构特性对比
python核心编程 python3提供了丰富且高效的数据结构,以下是核心类型对比:
| 类型 | 有序 | 可变 | 索引 | 键查找 | 典型用途 |
|---|---|---|---|---|---|
list | ✓ | ✓ | 整数索引 | × | 顺序存储、动态数组 |
tuple | ✓ | × | 整数索引 | × | 不可变序列、函数返回值 |
dict | ✓ (3.7+) | ✓ | × | ✓ (键) | 键值映射、配置存储 |
set | × | ✓ | × | × | 去重、集合运算 |
deque | ✓ | ✓ | 整数索引 | × | 双端队列、队列/栈 |
Counter | × | ✓ | 键索引 | ✓ (键) | 计数统计、频率分析 |
〈二〉列表推导式与生成器表达式
python核心编程 python3的列表推导式(List Comprehension)提供了一种简洁的列表构建方式:
# 生成平方数列表
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 过滤偶数平方数
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
# 嵌套列表推导式(矩阵转置)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose = [[row[i] for row in matrix] for i in range(3)]
print(transpose) # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
生成器表达式(Generator Expression)节省内存,适用于大数据处理:
# 生成器表达式(惰性求值)
gen = (x**2 for x in range(1000000))
print(next(gen)) # 0
print(next(gen)) # 1
# 内存占用极低,仅保存生成规则
# 对比列表推导式(立即创建完整列表)
# lst = [x**2 for x in range(1000000)] # 占用大量内存
〈三〉字典高级用法与性能优化
1. 字典合并与解包
Python 3.9+支持字典合并运算符(|):
config1 = {"host": "localhost", "port": 8000}
config2 = {"port": 8080, "debug": True}
# 新字典合并(config2覆盖config1)
merged = config1 | config2
print(merged) # {'host': 'localhost', 'port': 8080, 'debug': True}
# 就地更新
config1 |= config2
print(config1) # {'host': 'localhost', 'port': 8080, 'debug': True}
2. 字典默认值处理
使用defaultdict避免KeyError:
from collections import defaultdict
# 统计单词出现次数
words = ["python", "core", "programming", "python", "data", "python"]
counts = defaultdict(int)
for word in words:
counts[word] += 1
print(dict(counts)) # {'python': 3, 'core': 1, 'programming': 1, 'data': 1}
3. 字典视图对象
dict.keys()、dict.values()、dict.items()返回视图对象,支持集合操作:
dict1 = {"a": 1, "b": 2, "c": 3}
dict2 = {"b": 20, "c": 30, "d": 40}
# 键交集
common_keys = dict1.keys() & dict2.keys()
print(common_keys) # {'b', 'c'}
# 键差集
only_in_dict1 = dict1.keys() - dict2.keys()
print(only_in_dict1) # {'a'}
〔〕 面向对象编程体系
〈一〉类定义与实例化机制
python核心编程 python3的面向对象模型基于鸭子类型(Duck Typing)和多态性,支持封装、继承与多态三大特性:
class DatabaseConnection:
"""数据库连接类"""
def __init__(self, host, port, user, password):
"""构造函数:初始化连接参数"""
self.host = host
self.port = port
self.user = user
self.__password = password # 私有属性(名称重整)
self._is_connected = False
def connect(self):
"""建立数据库连接"""
print(f"连接到{self.host}:{self.port}...")
self._is_connected = True
def query(self, sql):
"""执行查询语句"""
if not self._is_connected:
raise RuntimeError("未连接数据库")
print(f"执行SQL:{sql}")
return "查询结果"
def close(self):
"""关闭连接"""
if self._is_connected:
print("连接已关闭")
self._is_connected = False
@property
def connection_info(self):
"""连接信息属性(只读)"""
return f"{self.user}@{self.host}:{self.port}"
@staticmethod
def validate_host(host):
"""静态方法:验证主机名格式"""
import re
pattern = r'^[a-zA-Z0-9.-]+$'
return bool(re.match(pattern, host))
@classmethod
def from_config(cls, config_path):
"""类方法:从配置文件创建实例"""
import json
with open(config_path) as f:
config = json.load(f)
return cls(**config)
# 使用示例
conn = DatabaseConnection("localhost", 3306, "root", "secret123")
print(conn.connection_info) # root@localhost:3306
print(DatabaseConnection.validate_host("my-db-server")) # True
# 从配置创建
# conn2 = DatabaseConnection.from_config("config.json")
〈二〉特殊方法(魔术方法)详解
python核心编程 python3通过特殊方法实现运算符重载与自定义行为:
| 方法名 | 触发场景 | 示例 |
|---|---|---|
__init__ | 实例创建 | obj = MyClass() |
__str__ | str(obj)或print(obj) | 返回用户友好字符串 |
__repr__ | repr(obj)或交互式解释器 | 返回开发者友好字符串 |
__len__ | len(obj) | 返回对象长度 |
__getitem__ | obj[key] | 支持索引/键访问 |
__setitem__ | obj[key] = value | 支持赋值操作 |
__iter__ | for item in obj | 使对象可迭代 |
__call__ | obj() | 使对象可调用 |
__enter__/__exit__ | with obj: | 支持上下文管理器 |
〈三〉抽象基类与多态实现
使用abc模块实现抽象基类,强制子类实现特定方法:
from abc import ABC, abstractmethod
class Shape(ABC):
"""图形抽象基类"""
@abstractmethod
def area(self):
"""计算面积"""
pass
@abstractmethod
def perimeter(self):
"""计算周长"""
pass
class Circle(Shape):
"""圆形实现"""
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
def perimeter(self):
return 2 * 3.14159 * self.radius
class Rectangle(Shape):
"""矩形实现"""
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
# 多态使用
shapes = [Circle(5), Rectangle(4, 6)]
for shape in shapes:
print(f"{shape.__class__.__name__}:面积={shape.area():.2f},周长={shape.perimeter():.2f}")
↑↓ 文件与IO操作体系
〈一〉文本文件读写最佳实践
python核心编程 python3推荐使用with语句确保文件正确关闭:
# 写入文本文件
with open("data.txt", "w", encoding="utf-8") as f:
f.write("Python核心编程\n")
f.write("python3权威指南\n")
# 读取文本文件
with open("data.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
for line in lines:
print(line.strip())
# 追加内容
with open("data.txt", "a", encoding="utf-8") as f:
f.write("新版特性详解\n")
1. 文件路径处理
使用pathlib模块统一处理路径(Python 3.4+):
from pathlib import Path
# 创建路径对象
base_dir = Path("/var/www/html")
data_dir = base_dir / "data" / "2024"
# 创建目录(包括父目录)
data_dir.mkdir(parents=True, exist_ok=True)
# 写入文件
file_path = data_dir / "report.txt"
file_path.write_text("Python核心编程 python3\n", encoding="utf-8")
# 读取文件
content = file_path.read_text(encoding="utf-8")
print(content)
# 遍历目录
for file in data_dir.glob("*.txt"):
print(f"找到文件:{file.name}")
〈二〉二进制文件处理与JSON序列化
1. 图像文件读写
# 读取二进制文件(如图片)
with open("image.png", "rb") as f:
data = f.read()
print(f"文件大小:{len(data)} 字节")
# 写入二进制文件
with open("copy.png", "wb") as f:
f.write(data)
2. JSON数据处理
import json
# Python对象转JSON字符串
data = {
"name": "Python核心编程",
"version": 3.13,
"topics": ["基础语法", "数据结构", "网络编程"],
"is_active": True,
"metadata": None
}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# JSON字符串转Python对象
parsed = json.loads(json_str)
print(parsed["topics"]) # ['基础语法', '数据结构', '网络编程']
# 从文件读取JSON
with open("config.json", "r", encoding="utf-8") as f:
config = json.load(f)
〈三〉CSV与Excel数据处理
1. CSV文件读写(标准库)
import csv
# 写入CSV
with open("data.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["姓名", "年龄", "城市"])
writer.writerow(["张三", 28, "成都"])
writer.writerow(["李四", 32, "成都"])
# 读取CSV
with open("data.csv", "r", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
print(row)
2. Excel文件处理(pandas)
import pandas as pd
# 创建DataFrame
df = pd.DataFrame({
"姓名": ["张三", "李四", "王五"],
"年龄": [28, 32, 25],
"城市": ["成都", "成都", "绵阳"]
})
# 写入Excel
df.to_excel("report.xlsx", index=False, sheet_name="数据")
# 读取Excel
df_read = pd.read_excel("report.xlsx")
print(df_read.head())
↖↗ 网络编程与协议实现
〈一〉socket编程基础
python核心编程 python3的socket模块提供底层网络通信能力:
# 服务器端
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 8080))
server.listen(5)
print("服务器启动,监听端口8080...")
while True:
client, addr = server.accept()
print(f"连接来自:{addr}")
data = client.recv(1024)
if data:
client.sendall(f"收到:{data.decode()}".encode())
client.close()
# 客户端
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("localhost", 8080))
client.sendall("Python核心编程 python3".encode())
response = client.recv(1024)
print("服务器响应:", response.decode())
client.close()
〈二〉HTTP请求处理
1. requests库基础用法
import requests
# GET请求
response = requests.get("https://api.github.com/repos/python/cpython")
print(f"状态码:{response.status_code}")
print(f"JSON数据:{response.json()['description']}")
# POST请求(JSON数据)
payload = {"name": "Python核心编程", "version": "3.13"}
headers = {"Content-Type": "application/json"}
res = requests.post("https://httpbin.org/post",
json=payload, headers=headers)
print(res.json()["json"])
# 带超时和重试的请求
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
session = requests.Session()
retry = Retry(total=3, backoff_factor=0.3, status_forcelist=[500, 502, 503])
adapter = HTTPAdapter(max_retries=retry)
session.mount("http://", adapter)
session.mount("https://", adapter)
response = session.get("https://httpbin.org/delay/3", timeout=5)
print(response.json())
2. 自定义HTTP服务器(http.server)
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
response = {"status": "success", "message": "python核心编程 python3"}
self.wfile.write(json.dumps(response).encode())
def do_POST(self):
content_length = int(self.headers.get("Content-Length", 0))
post_data = self.rfile.read(content_length).decode()
self.send_response(201)
self.send_header("Content-Type", "application/json")
self.end_headers()
response = {"received": post_data, "echo": "ok"}
self.wfile.write(json.dumps(response).encode())
server = HTTPServer(("localhost", 8000), MyHandler)
print("HTTP服务器启动:http://localhost:8000")
server.serve_forever()
〈三〉邮件发送与接收
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 发送邮件
def send_email(to_addr, subject, body):
msg = MIMEMultipart()
msg["From"] = "sender@example.com"
msg["To"] = to_addr
msg["Subject"] = subject
msg.attach(MIMEText(body, "plain", "utf-8"))
with smtplib.SMTP_SSL("smtp.example.com", 465) as server:
server.login("sender@example.com", "password")
server.send_message(msg)
send_email("receiver@example.com", "Python核心编程", "欢迎学习python3!")
# 接收邮件(POP3)
import poplib
def check_email():
server = poplib.POP3_SSL("pop.example.com")
server.user("sender@example.com")
server.pass_("password")
# 获取邮件列表
num_messages = len(server.list()[1])
print(f"收件箱共有 {num_messages} 封邮件")
# 获取最新邮件
if num_messages > 0:
lines = server.retr(num_messages)[1]
msg = b"\n".join(lines).decode()
print("最新邮件内容预览:", msg[:200])
server.quit()
check_email()
↘↙ 并发与异步编程
〈一〉多线程编程
python核心编程 python3使用threading模块实现多线程:
import threading
import time
def worker(name, delay):
"""工作线程函数"""
for i in range(3):
print(f"{name} - 工作 {i+1}")
time.sleep(delay)
# 创建线程
t1 = threading.Thread(target=worker, args=("线程A", 0.5))
t2 = threading.Thread(target=worker, args=("线程B", 0.7))
# 启动线程
t1.start()
t2.start()
# 等待线程完成
t1.join()
t2.join()
print("所有线程完成")
线程同步机制
import threading
class Counter:
def __init__(self):
self.value = 0
self.lock = threading.Lock()
def increment(self):
with self.lock:
self.value += 1
print(f"当前值:{self.value}")
counter = Counter()
def worker():
for _ in range(5):
counter.increment()
threads = [threading.Thread(target=worker) for _ in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"最终计数:{counter.value}") # 精确为15
〈二〉asyncio异步编程
Python 3.7+的asyncio提供原生异步IO支持:
import asyncio
async def fetch_data(source, delay):
"""模拟异步数据获取"""
print(f"开始获取 {source} 数据...")
await asyncio.sleep(delay)
print(f"完成获取 {source} 数据")
return f"{source} 数据内容"
async def main():
# 并发执行多个任务
tasks = [
fetch_data("数据库", 1.5),
fetch_data("API", 1.0),
fetch_data("缓存", 0.5)
]
results = await asyncio.gather(*tasks)
print("所有数据获取完成:", results)
# 运行异步程序
asyncio.run(main())
异步HTTP请求(aiohttp)
import aiohttp
import asyncio
async def fetch_url(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
"https://httpbin.org/delay/1",
"https://httpbin.org/delay/2",
"https://httpbin.org/delay/1"
]
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
responses = await asyncio.gather(*tasks)
print(f"成功获取 {len(responses)} 个页面")
asyncio.run(main())
〈三〉进程池与multiprocessing
使用multiprocessing模块绕过GIL限制,实现CPU密集型任务并行:
import multiprocessing
import time
def cpu_bound_task(n):
"""CPU密集型任务:计算素数"""
primes = []
for num in range(2, n):
is_prime = True
for i in range(2, int(num**0.5)+1):
if num % i == 0:
is_prime = False
break
if is_prime:
primes.append(num)
return len(primes)
def main():
numbers = [10000, 15000, 20000]
# 单进程执行
start = time.time()
results = [cpu_bound_task(n) for n in numbers]
single_time = time.time() - start
print(f"单进程耗时:{single_time:.2f}秒")
# 多进程执行
start = time.time()
with multiprocessing.Pool() as pool:
results = pool.map(cpu_bound_task, numbers)
multi_time = time.time() - start
print(f"多进程耗时:{multi_time:.2f}秒")
print(f"加速比:{single_time/multi_time:.2f}x")
if __name__ == "__main__":
main()
♀♂ Web开发技术栈
〈一〉Flask框架核心功能
python核心编程 python3开发Web应用的轻量级框架:
from flask import Flask, request, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # 支持跨域请求
# 路由定义
@app.route("/")
def index():
return "Python核心编程 python3 Web服务"
@app.route("/api/user", methods=["GET", "POST"])
def user():
if request.method == "POST":
data = request.json
return jsonify({"status": "success", "user": data}), 201
else:
return jsonify({"name": "游客", "role": "guest"})
# 路径参数
@app.route("/api/users/")
def get_user(user_id):
users = {
1: {"id": 1, "name": "张三"},
2: {"id": 2, "name": "李四"}
}
user = users.get(user_id)
if user:
return jsonify(user)
return jsonify({"error": "用户不存在"}), 404
# 错误处理
@app.errorhandler(404)
def not_found(e):
return jsonify({"error": "请求路径不存在"}), 404
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=5000)
〈二〉Django框架核心组件
企业级Web框架的ORM与模板系统:
# models.py - 数据模型定义
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.CharField(max_length=50)
created_at = models.DateTimeField(auto_now_add=True)
tags = models.ManyToManyField("Tag", blank=True)
class Meta:
db_table = "articles"
ordering = ["-created_at"]
def __str__(self):
return self.title
class Tag(models.Model):
name = models.CharField(max_length=50, unique=True)
class Meta:
db_table = "tags"
def __str__(self):
return self.name
# views.py - 视图函数
from django.shortcuts import render, get_object_or_404
from .models import Article, Tag
def article_list(request):
articles = Article.objects.all()[:10]
return render(request, "articles.html", {"articles": articles})
def article_detail(request, pk):
article = get_object_or_404(Article, pk=pk)
return render(request, "article_detail.html", {"article": article})
def tag_cloud(request):
tags = Tag.objects.annotate(num_articles=models.Count("article"))
return render(request, "tag_cloud.html", {"tags": tags})
模板示例
<!-- articles.html -->
<h1>文章列表</h1>
<ul>
{% for article in articles %}
<li><a href="{% url 'article_detail' article.pk %}">
{{ article.title }} ({{ article.author }})
</a></li>
{% empty %}
<li>暂无文章</li>
{% endfor %}
</ul>
〈三〉RESTful API设计规范
1. URL设计原则
- 使用名词复数:/users、/articles、/comments
- 版本控制:/api/v1/users
- 过滤与排序:/articles?author=python&limit=20&sort=-created_at
- 嵌套资源:/users/123/articles(用户123的文章)
2. HTTP方法语义
| 方法 | 用途 | 幂等性 |
|---|---|---|
| GET | 获取资源 | ✓ |
| POST | 创建资源 | × |
| PUT | 替换资源(完整更新) | ✓ |
| PATCH | 部分更新资源 | × |
| DELETE | 删除资源 | ✓ |
3. 响应状态码
| 状态码 | 含义 | 示例 |
|---|---|---|
| 200 | 请求成功 | GET /users/1 |
| 201 | 资源创建成功 | POST /users |
| 204 | 无内容(删除成功) | DELETE /users/1 |
| 400 | 请求参数错误 | 缺少必填字段 |
| 401 | 未认证 | 缺少有效Token |
| 403 | 禁止访问 | 权限不足 |
| 404 | 资源不存在 | 用户ID无效 |
| 429 | 请求过多 | 超出速率限制 |
| 500 | 服务器内部错误 | 数据库连接失败 |
〓 自动化运维与脚本开发
〈一〉系统管理自动化
使用subprocess执行系统命令:
import subprocess
# 执行简单命令
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print(result.stdout)
# 执行带参数的命令
cmd = ["grep", "python", "/var/log/syslog"]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
print("找到相关日志:")
print(result.stdout)
# 执行复杂命令链
process = subprocess.Popen(
["dmesg"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
grep_process = subprocess.Popen(
["grep", "eth0"],
stdin=process.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
process.stdout.close() # 允许grep进程接收数据
output, _ = grep_process.communicate()
print("网络接口日志:")
print(output)
1. 文件监控(watchdog)
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import time
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
print(f"检测到修改:{event.src_path}")
def on_created(self, event):
print(f"新文件创建:{event.src_path}")
if __name__ == "__main__":
path = "/tmp/test"
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
〈二〉定时任务与调度
1. schedule库基础
import schedule
import time
def backup_database():
print("开始数据库备份...")
# 实际备份逻辑
print("备份完成")
def send_report():
print("发送日报...")
# 实际发送逻辑
print("发送完成")
# 每天10:30执行
schedule.every().day.at("10:30").do(backup_database)
# 每30分钟执行
schedule.every(30).minutes.do(send_report)
# 每周一9:00执行
schedule.every().monday.at("09:00").do(lambda: print("周一例会"))
while True:
schedule.run_pending()
time.sleep(1)
2. APScheduler企业级调度
from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime
def job(text):
print(f"任务执行:{text} at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
scheduler = BlockingScheduler()
# Cron表达式(秒 分 时 日 月 周)
scheduler.add_job(job, 'cron', second='0', minute='*/5',
args=['每5分钟执行'])
# 固定间隔执行
scheduler.add_job(job, 'interval', minutes=30,
args=['每30分钟执行'])
# 单次执行
scheduler.add_job(job, 'date', run_date='2025-01-01 00:00:00',
args=['新年首日执行'])
scheduler.start()
〈三〉日志系统构建
使用logging模块构建企业级日志系统:
import logging
from logging.handlers import RotatingFileHandler
import os
# 创建日志目录
os.makedirs("logs", exist_ok=True)
# 配置日志格式
formatter = logging.Formatter(
"%(asctime)s [%(levelname)-8s] %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
# 控制台处理器
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(formatter)
# 文件处理器(轮转)
file_handler = RotatingFileHandler(
"logs/app.log", maxBytes=10*1024*1024, backupCount=5
)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
# 错误日志处理器
error_handler = RotatingFileHandler(
"logs/error.log", maxBytes=10*1024*1024, backupCount=5
)
error_handler.setLevel(logging.ERROR)
error_handler.setFormatter(formatter)
# 配置根logger
logger = logging.getLogger("python_core")
logger.setLevel(logging.DEBUG)
logger.addHandler(console_handler)
logger.addHandler(file_handler)
logger.addHandler(error_handler)
# 使用日志
logger.info("应用启动")
logger.debug("调试信息")
try:
1 / 0
except Exception:
logger.exception("发生异常")
▲▼ 数据分析与可视化
〈一〉pandas核心操作
使用python核心编程 python3进行数据处理:
import pandas as pd
import numpy as np
# 创建DataFrame
df = pd.DataFrame({
"姓名": ["张三", "李四", "王五", "赵六"],
"年龄": [28, 32, 25, 30],
"城市": ["成都", "成都", "绵阳", "成都"],
"工资": [8000, 12000, 6000, 9500]
})
# 基本信息
print(df.info())
print(df.describe())
# 数据筛选
chengdu_workers = df[df["城市"] == "成都"]
high_salary = df[df["工资"] > 9000]
# 分组聚合
city_stats = df.groupby("城市").agg({
"年龄": "mean",
"工资": ["mean", "max", "min"]
}).round(2)
print(city_stats)
# 数据透视表
pivot = pd.pivot_table(
df,
values="工资",
index="城市",
columns="年龄",
aggfunc="mean",
fill_value=0
)
print(pivot)
〈二〉matplotlib可视化
import matplotlib.pyplot as plt
import numpy as np
# 创建数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# 创建图形
plt.figure(figsize=(10, 6))
# 绘制折线图
plt.plot(x, y1, label="sin(x)", color="#037ef3", linewidth=2)
plt.plot(x, y2, label="cos(x)", color="#ff6b35", linestyle="--", linewidth=2)
# 添加标题和标签
plt.title("三角函数图像", fontsize=16)
plt.xlabel("x", fontsize=12)
plt.ylabel("y", fontsize=12)
# 添加图例
plt.legend(fontsize=12)
# 添加网格
plt.grid(True, linestyle=":", alpha=0.7)
# 保存图片
plt.savefig("trig_functions.png", dpi=300, bbox_inches="tight")
plt.show()
1. 专业统计图表
import matplotlib.pyplot as plt
# 数据
categories = ["基础语法", "数据结构", "网络编程", "并发编程", "Web开发"]
values = [25, 20, 15, 10, 30]
colors = ["#037ef3", "#0266c2", "#015ab7", "#004e9d", "#004283"]
# 创建子图
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))
# 饼图
ax1.pie(values, labels=categories, colors=colors, autopct="%1.1f%%",
startangle=90, explode=[0.05]*5)
ax1.set_title("Python核心编程 python3学习内容分布", fontsize=14)
# 条形图
bars = ax2.bar(categories, values, color=colors, edgecolor="white", width=0.6)
ax2.set_ylabel("占比 (%)", fontsize=12)
ax2.set_title("学习内容重要性分布", fontsize=14)
ax2.set_ylim(0, 35)
# 添加数值标签
for bar, value in zip(bars, values):
ax2.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5,
f"{value}%", ha="center", fontsize=11)
plt.tight_layout()
plt.savefig("learning_distribution.png", dpi=300, bbox_inches="tight")
plt.show()
〈三〉数据清洗与预处理
1. 处理缺失值
import pandas as pd
import numpy as np
df = pd.DataFrame({
"姓名": ["张三", "李四", None, "赵六"],
"年龄": [28, np.nan, 25, 30],
"工资": [8000, 12000, 6000, None]
})
# 检查缺失值
print(df.isnull().sum())
# 删除含缺失值的行
df_dropped = df.dropna()
# 填充缺失值
df_filled = df.fillna({
"姓名": "未知",
"年龄": df["年龄"].mean(),
"工资": df["工资"].median()
})
# 前向填充
df_ffill = df.ffill()
# 后向填充
df_bfill = df.bfill()
2. 异常值检测
from scipy import stats
# 使用Z-score检测异常值
z_scores = np.abs(stats.zscore(df["工资"]))
threshold = 2
outliers = df[z_scores > threshold]
print("异常值:")
print(outliers)
# 使用IQR方法
Q1 = df["工资"].quantile(0.25)
Q3 = df["工资"].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
outliers_iqr = df[(df["工资"] < lower_bound) | (df["工资"] > upper_bound)]
print("IQR方法检测的异常值:")
print(outliers_iqr)
※ 人工智能与机器学习入门
〈一〉scikit-learn基础应用
使用python核心编程 python3进行机器学习:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
# 加载数据集
iris = load_iris()
X, y = iris.data, iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# 创建模型
model = RandomForestClassifier(n_estimators=100, random_state=42)
# 训练模型
model.fit(X_train, y_train)
# 预测
y_pred = model.predict(X_test)
# 评估
accuracy = accuracy_score(y_test, y_pred)
print(f"准确率:{accuracy:.2%}")
# 详细报告
print("\n分类报告:")
print(classification_report(y_test, y_pred, target_names=iris.target_names))
〈二〉文本处理与NLP
1. jieba分词
import jieba
text = "Python核心编程 python3是一本权威指南,涵盖从基础到高级的全部内容"
# 精确模式
words = jieba.lcut(text)
print("精确模式:", "/".join(words))
# 全模式
full_words = jieba.lcut(text, cut_all=True)
print("全模式:", "/".join(full_words))
# 搜索引擎模式
search_words = jieba.lcut_for_search(text)
print("搜索引擎模式:", "/".join(search_words))
2. 词频统计
from collections import Counter
import re
# 停用词列表
stop_words = {"的", "是", "在", "与", "和", "及", "或", "一个"}
# 文本预处理
text = """Python核心编程 python3是一本权威指南。
python3最新特性包括结构化模式匹配、性能优化等。
学习python核心编程 python3,掌握现代编程技术。"""
# 清洗文本
cleaned = re.sub(r"[^\u4e00-\u9fa5a-zA-Z0-9]", "", text)
# 分词
words = jieba.lcut(cleaned)
# 过滤停用词
filtered = [w for w in words if w not in stop_words and len(w) > 1]
# 统计词频
word_counts = Counter(filtered)
top_words = word_counts.most_common(10)
print("高频词:")
for word, count in top_words:
print(f"{word}: {count}")
〈三〉深度学习入门(PyTorch)
import torch
import torch.nn as nn
import torch.optim as optim
# 数据准备
X = torch.tensor([[0.0], [1.0], [2.0], [3.0]])
y = torch.tensor([[1.0], [3.0], [5.0], [7.0]])
# 定义模型
class LinearModel(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(1, 1)
def forward(self, x):
return self.linear(x)
model = LinearModel()
# 损失函数和优化器
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# 训练循环
for epoch in range(100):
optimizer.zero_grad()
outputs = model(X)
loss = criterion(outputs, y)
loss.backward()
optimizer.step()
if (epoch + 1) % 20 == 0:
print(f"Epoch [{epoch+1}/100], Loss: {loss.item():.4f}")
# 测试预测
test_data = torch.tensor([[4.0], [5.0]])
with torch.no_grad():
predictions = model(test_data)
print("\n预测结果:")
for i, pred in enumerate(predictions):
print(f"输入 {test_data[i].item()} → 输出 {pred.item():.2f}")
〔〕 网友们都还关心
1. python核心编程 python3与Python 2.x有何本质区别?
- 字符串类型:Python 3统一使用Unicode字符串(str),而Python 2区分str和unicode
- 整数除法:Python 3中/总是返回浮点数,//才执行整除
- print函数:Python 3中print是函数,必须使用括号
- 编码声明:Python 3默认UTF-8编码,无需额外声明
- 迭代器:Python 3中range()返回迭代器,更节省内存
- 异常处理:except语句语法改变,必须使用as关键字
2. python核心编程 python3适合哪些开发方向?
- Web开发:Django、Flask、FastAPI等框架成熟稳定
- 数据分析:pandas、NumPy、Matplotlib构成完整生态
- 人工智能:TensorFlow、PyTorch、scikit-learn支持强大
- 自动化运维:Ansible、SaltStack等工具基于Python开发
- 网络爬虫:Scrapy、BeautifulSoup、Selenium等库丰富
- 桌面应用:PyQt、Tkinter、Kivy支持GUI开发
- 游戏开发:Pygame、Arcade等框架适用于小型游戏
- 科学计算:SciPy、SymPy等库支持高级数学运算
3. 如何高效学习python核心编程 python3?
- 基础优先:掌握语法、数据结构、函数等核心概念
- 项目驱动:通过小型项目巩固知识(如爬虫、数据分析)
- 阅读源码:学习优秀开源项目代码风格与设计模式
- 持续实践:每天编写代码,保持编程思维活跃
- 社区参与:加入Python中文社区,参与技术讨论
- 版本跟进:关注Python新特性,及时更新知识体系
- 类型提示:学习并应用Type Hints提升代码质量
- 性能优化:掌握profiling工具,编写高效代码
4. python核心编程 python3在企业级应用中的优势?
- 开发效率高:代码简洁,开发周期短,维护成本低
- 生态成熟:拥有海量第三方库,覆盖各领域需求
- 跨平台性好:一次编写,多平台运行(Windows/Linux/macOS)
- 团队协作佳:代码可读性强,降低沟通成本
- 社区支持强:活跃社区提供及时技术支持与文档
- 集成能力强:易于与Java、C/C++等语言集成
- DevOps友好:Ansible、SaltStack等自动化工具基于Python
- 云原生支持:Kubernetes、OpenStack等云平台组件多用Python
5. python核心编程 python3与其他语言对比如何?
- vs Java:Python开发效率更高,Java性能更优;Python动态类型,Java静态类型
- vs JavaScript:Python更适合后端与数据处理,JavaScript主导前端开发
- vs C++:Python开发速度快,C++性能极限高;Python内存自动管理
- vs Go:Python生态更丰富,Go并发性能更优;Go编译型,Python解释型
- vs Ruby:两者语法相似,Python社区更大,应用范围更广
- vs PHP:Python更适合现代Web开发,PHP传统CMS生态成熟
6. python核心编程 python3学习资源推荐?
- 官方文档:docs.python.org/zh-cn/3(最权威)
- 书籍:《python核心编程 python3》《流畅的Python》《Python Cookbook》
- 在线课程:Coursera、Udemy、慕课网Python专题
- 开源项目:GitHub搜索"python core"、"python3 examples"
- 技术博客:Real Python、Python Weekly、知乎Python话题
- 社区论坛:Stack Overflow、Python中文社区、V2EX编程板块
- 工具网站:LeetCode(算法练习)、Replit(在线IDE)
- 视频频道:YouTube的Corey Schafer、B站的科技美学
〔〕 常见问题解答(FAQ)
Q1:python核心编程 python3安装时如何选择版本?
建议选择最新稳定版本(当前为3.13.1)。如需生产环境兼容性,可选择LTS版本(如3.11)。避免使用已停止维护的Python 2.x版本。安装时勾选"Add Python to PATH"选项,便于命令行使用。
Q2:如何验证python核心编程 python3安装成功?
在终端执行python --version或python3 --version,应显示类似Python 3.13.1的输出。进入交互式解释器执行print("Hello, Python!"),确认无错误输出。
Q3:python核心编程 python3与Anaconda如何选择?
基础开发使用官方Python安装包即可;数据科学与机器学习推荐Anaconda,其预装了NumPy、pandas、scikit-learn等科学计算库。生产环境建议使用虚拟环境(venv或conda)隔离项目依赖。
Q4:python核心编程 python3开发环境推荐配置?
编辑器:VS Code(配合Python插件)、PyCharm Community Edition;终端:Windows用户推荐PowerShell + Windows Terminal;Linux/macOS用户直接使用系统终端;版本管理:pyenv管理多版本Python;包管理:pip配合requirements.txt或pyproject.toml。
Q5:python核心编程 python3学习路径建议?
基础语法(2周)→ 数据结构与算法(3周)→ 面向对象编程(2周)→ 标准库深度(2周)→ 项目实战(4周)→ 专项深化(Web/数据/AI方向)→ 持续学习新技术。建议每阶段配套小型项目巩固知识。