Python是一门高效、易读、功能强大的编程语言,自1991年首次发布以来,已发展成为全球最受欢迎的编程语言之一。其设计哲学强调代码可读性与简洁语法,广泛应用于Web开发、数据分析、人工智能、自动化运维、科学计算等领域。
本教程面向零基础至进阶学习者,系统梳理Python核心知识点与实战技巧,结合真实场景案例,帮助您从入门到精通,构建扎实的Python开发能力。
Python之所以广受欢迎,源于其独特优势:
本教程内容严格遵循现代Python标准(Python 3.10+),所有示例均已实测通过,确保实用性与前瞻性兼备。建议学习者边学边练,动手编写代码,培养“编程直觉”。
Python解释器是运行Python代码的核心组件。当前主流版本为Python 3.x系列,推荐使用最新稳定版(截至2025年为3.12.3)。
Windows系统安装步骤:
python --version 验证。macOS系统安装建议:
brew install pythonLinux系统(Ubuntu/Debian):
python3 --version 检查。sudo apt update && sudo apt install python3 python3-pip推荐以下三款主流IDE,兼顾初学者友好性与专业开发需求:
| IDE名称 | 特点 | 适用场景 |
|---|---|---|
| PyCharm | 功能最全,智能提示强,支持Django/Flask调试 | 专业开发、团队协作 |
| VS Code | 轻量级,插件丰富,免费开源 | 全栈开发、Web项目 |
| Thonny | 专为教学设计,内置调试器与变量查看 | 零基础入门、课堂实验 |
为避免项目间依赖冲突,必须使用虚拟环境隔离依赖包:
python -m venv myenv # Windows激活:myenv\Scripts\activate # Linux/macOS激活:source myenv/bin/activate # 退出虚拟环境:deactivate
激活后,pip install安装的包仅作用于当前环境,确保项目可复现性。
# -*- coding: utf-8 -*-black 工具自动统一风格:pip install black,运行 black your_script.pytyping 模块增强代码可读性:def greet(name: str) -> str: ...Python是动态类型语言,变量无需声明类型,直接赋值即可:
name = "张三" # 字符串 str
age = 25 # 整数 int
height = 1.75 # 浮点数 float
is_student = True # 布尔值 bool
scores = [95, 88, 92] # 列表 list
info = {"姓名":"李四", "年龄":22} # 字典 dict
常见类型转换:
int("123") → 123str(3.14) → "3.14"list("abc") → ['a', 'b', 'c']bool(0) → False;bool("abc") → True条件判断(if-elif-else):
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"
循环结构(for/while):
for i in range(5):
print(i) # 输出 0,1,2,3,4
i = 0
while i < 3:
print("循环中...", i)
i += 1
break与continue:
break:提前终止当前层循环continue:跳过本次循环剩余部分,进入下一轮函数是代码复用的基本单元:
def add(a, b):
"""返回两数之和"""
return a + b
result = add(3, 5) # result = 8
默认参数与可变参数:
def greet(name, msg="你好"):
print(f"{msg}, {name}!")
greet("王五") # 输出:你好, 王五!
greet("赵六", "早上好") # 输出:早上好, 赵六!
lambda匿名函数(适用于简单逻辑):
multiply = lambda x, y: x * y print(multiply(4, 5)) # 输出:20
模块是Python代码文件,包是模块的集合。常用导入方式:
import math → 使用 math.sqrt(16)from datetime import datetime → 直接使用 datetime.now()import numpy as np → 别名简化调用自定义模块示例:
# mymath.py 文件内容
def square(x):
return x * x
def cube(x):
return x ** 3
# main.py 中使用 import mymath print(mymath.square(4)) # 输出:16
文本文件读写:
# 读取文本文件
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# 写入文本文件
with open("output.txt", "w", encoding="utf-8") as f:
f.write("第一行内容\n第二行内容")
CSV文件处理(使用内置csv模块):
import csv
# 读取CSV
with open("students.csv", "r", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["姓名"], row["分数"])
JSON数据处理:
import json
# 字典转JSON字符串
data = {"name":"张三", "age":25}
json_str = json.dumps(data, ensure_ascii=False)
print(json_str) # {"name":"张三", "age":25}
# JSON字符串转字典
parsed = json.loads(json_str)
print(parsed["name"]) # 张三
用于文本模式匹配与提取:
import re text = "订单号:AB123456789CN,金额:¥99.99" # 提取订单号(字母+数字) order_no = re.search(r"订单号:([A-Z0-9]+)", text).group(1) # 提取金额数字 amount = re.search(r"¥(\d+\.?\d*)", text).group(1) print(order_no, amount) # AB123456789CN 99.99
时间格式化与计算:
from datetime import datetime, timedelta
# 当前时间
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 2025-04-05 14:30:22
# 计算7天后日期
future = now + timedelta(days=7)
print(future.date()) # 2025-04-12
列表推导式(高效生成列表):
squares = [x**2 for x in range(10)] print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
字典推导式:
words = ["apple", "banana", "cherry"]
length = {word: len(word) for word in words}
print(length) # {'apple': 5, 'banana': 6, 'cherry': 6}
集合(set)去重与运算:
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a & b) # 交集:{3, 4}
print(a | b) # 并集:{1, 2, 3, 4, 5, 6}
print(a - b) # 差集:{1, 2}
安装Flask框架:
pip install flask
最小Web应用示例:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "欢迎访问Python Web首页!
"
@app.route("/user/")
def greet(name):
return f"你好,{name}!
"
if __name__ == "__main__":
app.run(debug=True)
运行后访问:http://localhost:5000/ 和 http://localhost:5000/user/小明
使用Jinja2模板引擎:
templates/ 目录,添加 index.htmlrender_template 渲染# app.py
@app.route("/profile/")
def profile(username):
user_data = {"name": username, "score": 92}
return render_template("profile.html", user=user_data)
模板文件 profile.html:
<!DOCTYPE html>
<html>
<body>
<h2>用户信息:</h2>
<p>姓名:{{ user.name }}</p>
<p>分数:{{ user.score }}</p>
</body>
</html>
GET与POST请求处理:
from flask import request
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
if username == "admin" and password == "123":
return "登录成功!
"
else:
return "用户名或密码错误!
"
return '''<form method="post">
用户名:<input name="username"><br>
密码:<input name="password" type="password"><br>
<input type="submit" value="登录">
</form>'''
返回JSON格式数据:
from flask import jsonify
@app.route("/api/user/1")
def get_user():
user = {"id": 1, "name": "李四", "email": "lisi@example.com"}
return jsonify(user)
前端可直接通过AJAX调用该接口,实现前后端分离架构。
1. 批量重命名文件
import os
folder = "D:/photos/"
for i, filename in enumerate(os.listdir(folder)):
if filename.endswith(".jpg"):
old_path = os.path.join(folder, filename)
new_name = f"旅行_{i+1}.jpg"
new_path = os.path.join(folder, new_name)
os.rename(old_path, new_path)
2. 自动生成周报(Word文档)
from docx import Document
from docx.shared import Inches
doc = Document()
doc.add_heading("工作周报", 0)
doc.add_paragraph("本周完成任务:")
doc.add_paragraph("1. 处理客户数据 120条")
doc.add_paragraph("2. 优化数据库查询脚本")
doc.add_picture("chart.png", width=Inches(4))
doc.save("周报_2025W14.docx")
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 发送文本邮件
msg = MIMEText("您好,这是一封自动发送的测试邮件。", "plain", "utf-8")
msg["From"] = Header("系统通知 ", "utf-8")
msg["To"] = Header("张三 ", "utf-8")
msg["Subject"] = Header("重要通知", "utf-8")
server = smtplib.SMTP_SSL("smtp.company.com", 465)
server.login("admin@company.com", "password123")
server.sendmail("admin@company.com", ["zhangsan@example.com"], msg.as_string())
server.quit()
模拟浏览器操作,实现网页数据抓取或表单提交:
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
driver = webdriver.Chrome()
driver.get("https://example.com/login")
driver.find_element(By.ID, "username").send_keys("testuser")
driver.find_element(By.ID, "password").send_keys("123456")
driver.find_element(By.XPATH, "//button[@type='submit']").click()
time.sleep(3)
print(driver.title) # 输出页面标题
driver.quit()
安装库:pip install pandas matplotlib
import pandas as pd
# 读取CSV数据
df = pd.read_csv("sales.csv")
# 查看前5行
print(df.head())
# 基本统计信息
print(df.describe())
# 按产品分类汇总销售额
sales_by_product = df.groupby("产品")["销售额"].sum().sort_values(ascending=False)
print(sales_by_product)
绘制柱状图:
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["SimHei"] # 解决中文乱码
plt.rcParams["axes.unicode_minus"] = False
products = sales_by_product.index
sales = sales_by_product.values
plt.figure(figsize=(10, 6))
plt.bar(products, sales, color="#037ef3")
plt.title("各产品销售额对比")
plt.xlabel("产品")
plt.ylabel("销售额(万元)")
plt.tight_layout()
plt.savefig("sales_chart.png")
某电商店铺2024年数据:
关键发现:
df.dropna() / df.fillna(0)df.drop_duplicates()df["日期"] = pd.to_datetime(df["日期"])目标:抓取豆瓣电影Top250前10页电影名称与评分
import requests
from bs4 import BeautifulSoup
import csv
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
with open("movies.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["排名", "电影名", "评分", "评价人数"])
for page in range(10):
url = f"https://movie.douban.com/top250?start={page*25}"
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
for item in soup.select("div.item"):
rank = item.select_one("em").text
title = item.select_one("span.title").text
rating = item.select_one("span.rating_num").text
people = item.select_one("span.rating_nums").next_sibling.next_sibling.text.strip("人评价")
with open("movies.csv", "a", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow([rank, title, rating, people])
常见反爬机制及对策:
time.sleep(2))或使用代理IP池除CSV外,还可存储至:
写入SQLite示例:
import sqlite3
conn = sqlite3.connect("movies.db")
cursor = conn.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS movies (
id INTEGER PRIMARY KEY,
rank INTEGER,
title TEXT,
rating REAL,
people INTEGER
)""")
# 插入数据(示例)
cursor.execute("INSERT INTO movies VALUES (?, ?, ?, ?, ?)",
(1, "肖申克的救赎", 9.7, 2500000))
conn.commit()
conn.close()
A:Python语法更简洁直观,代码量少,学习曲线平缓。Java需理解更多底层概念(如JVM、泛型、线程池),适合后续进阶。建议从Python入门,再根据职业方向选择扩展语言。
A:常见于文件读写或网络请求。解决步骤:
encoding="utf-8"headers={"Accept-Encoding": "gzip, deflate"}charset="utf8mb4"A:对于I/O密集型任务(如爬虫、Web服务),Python完全胜任;CPU密集型任务可通过以下方式优化:
阿里、腾讯等企业广泛使用Python处理高并发业务,证明其生产可用性。
A:
pip install -U pip setuptools 更新工具链A:基础编程(语法、逻辑)无需高深数学;但以下方向需数学支持:
建议先掌握基础编程,再根据兴趣方向补充数学知识。
A:推荐“3+1学习法”:
避免“只看不练”,建议使用LeetCode刷题巩固逻辑思维。