2024年最新Python编程入门教程从零基础到项目开发实战完整指南
为什么现在学Python正当时
说实话,2024年的Python和五年前已经不太一样了。现在的Python生态更加成熟,工具链也更加友好。无论你将来想做数据分析、人工智能、Web开发,还是自动化办公,Python都是绕不开的编程语言。
我见过太多初学者被劝退的经历:上来就讲语法细节、讲抽象概念,代码全是英文注释和数学符号,看得人头晕眼花。所以这篇教程我换个方式来讲——从你能理解的地方出发,一边学一边练,直到你能做出一个真正能用的项目。
第一步:把Python装好,别被环境劝退
装Python这件事,现在比五年前简单太多了。
推荐方式:用官方安装包
去官网 python.org 下载最新稳定版。2024年最新的稳定版是 Python 3.12.x,特性包括:
- 更快的启动速度(相比3.8快了约30%)
- 更好的类型提示支持
- 移除了一些废弃语法,写出来的代码更规范
下载完成后,安装时务必勾选 “Add Python to PATH”,这一步很多人会漏掉,导致后续命令找不到Python。
验证安装是否成功
打开终端(Windows用PowerShell或CMD,Mac用终端),输入:
python --version
如果输出类似 Python 3.12.4,说明安装成功了。
选一个趁手的编辑器
2024年最推荐的组合是 VS Code + Python插件。微软的VS Code免费、轻量、插件生态丰富。装完VS Code后,在扩展市场搜索 “Python” 并安装官方插件,它就会自动识别Python代码、提供语法高亮和智能提示。
第二步:第一个Python程序——你不需要理解一切
很多教程上来就讲”变量”“数据类型”“控制流”,我打算反着来。
我们先写一个真正能用的程序:
# hello.py —— 你的第一个Python程序
name = input("你好!请告诉我你的名字:")
print(f"欢迎你,{name}!Python学习之旅从这里开始 🚀")
运行这段代码(在终端输入 python hello.py),你会看到一个简单的交互程序。它做了三件事:
- 接收输入:
input()让你从键盘输入文字 - 存储数据:把输入的内容放进一个叫
name的变量里 - 输出结果:用
print()把欢迎语显示出来
f"..." 是 f-string,2024年Python最常用的字符串格式化方式,比老式的 % 或 .format() 都直观得多。
这段代码背后的关键概念
你不需要一次全懂,但有个大致印象就好:
- 变量:
name就是一个盒子,用来装你输入的名字 - 函数:
input()和print()都是内置函数,Python给你准备好了的工具 - 字符串:用引号括起来的文字,f-string 允许你在字符串里直接嵌入变量
第三步:Python的核心数据类型——把现实世界装进代码
数据是程序处理的东西。Python提供了五种最常用的数据类型,我们先从最基础的两种说起。
数字类型
# 整数 —— 没有任何小数点
age = 25
count = 100
# 浮点数 —— 带小数点的数字
price = 19.99
temperature = -3.5
# 基本的数学运算
result = (price * count) + age
print(f"总价计算:{result}") # 输出:总价计算:2024.0
字符串类型
字符串就是一段文字,用单引号、双引号或三引号都可以:
# 单引号和双引号效果一样
greeting1 = 'Hello'
greeting2 = "Hello"
# 三引号可以写多行文本
poem = """
床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。
"""
# 字符串常用操作
text = "Python Programming"
print(text.upper()) # PYTHON PROGRAMMING
print(text.lower()) # python programming
print(text.split(" ")) # ['Python', 'Programming']
print(len(text)) # 18(字符串长度)
print(text.replace("P", "J")) # Jython Jrogramming
列表——有序的盒子
列表是最常用的数据结构,可以存放任意类型的数据,而且是有序的:
fruits = ["苹果", "香蕉", "橙子", "葡萄"]
# 访问元素(索引从0开始!)
print(fruits[0]) # 苹果
print(fruits[2]) # 橙子
print(fruits[-1]) # 葡萄(-1表示最后一个)
# 修改元素
fruits[1] = "芒果"
print(fruits) # ['苹果', '芒果', '橙子', '葡萄']
# 添加元素
fruits.append("西瓜") # 添加到末尾
fruits.insert(0, "草莓") # 在指定位置插入
# 删除元素
fruits.remove("香蕉") # 按值删除
del fruits[0] # 按索引删除
last = fruits.pop() # 删除并返回最后一个元素
# 列表切片——非常实用
print(fruits[1:3]) # 取第2到第3个元素
print(fruits[:2]) # 取前2个
print(fruits[2:]) # 从第3个到末尾
# 列表推导式——Python程序员最常用的语法之一
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
字典——键值对的集合
字典像一本电话簿,通过”名字”找到”号码”:
student = {
"name": "小明",
"age": 18,
"grades": [85, 92, 78, 95],
"is_enrolled": True
}
# 访问值
print(student["name"]) # 小明
print(student.get("age", 0)) # 18(get方法可以设默认值)
# 添加/修改
student["email"] = "xiaoming@example.com"
student["age"] = 19
# 删除
del student["is_enrolled"]
# 遍历字典
for key, value in student.items():
print(f"{key}: {value}")
# 检查键是否存在
if "name" in student:
print("有这个名字")
布尔值和空值
# 布尔值只有两种:True 或 False
is_sunny = True
is_raining = False
# 空值用 None 表示
nothing = None
# 类型转换
print(int("100")) # 100(字符串转整数)
print(float("3.14")) # 3.14(字符串转浮点数)
print(str(100)) # "100"(整数转字符串)
print(bool(1)) # True(非零即真)
print(bool(0)) # False
print(bool("")) # False(空字符串为假)
第四步:控制流程——让程序学会”做选择”
现实世界不是直线前进的,程序也一样。Python提供了三种控制流程结构:条件判断、for循环、while循环。
条件判断:if / elif / else
score = 85
if score >= 90:
print("优秀!🌟")
elif score >= 80:
print("良好!👍")
elif score >= 60:
print("及格了,继续努力")
else:
print("需要加油了")
# 嵌套条件判断
age = 20
has_id = True
if age >= 18:
if has_id:
print("可以入场")
else:
print("请先带身份证")
else:
print("未成年人不允许入场")
三元表达式——一行搞定简单条件判断:
age = 20
status = "成年人" if age >= 18 else "未成年人"
print(status) # 成年人
# 也可以用于赋值
discount = 0.9 if age >= 60 else 1.0
for循环——遍历一切可迭代对象
# 遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
print(f"我喜欢吃{fruit}")
# range()函数——生成数字序列
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 8): # 2, 3, 4, 5, 6, 7
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8(步长为2)
print(i)
# 遍历字典
student = {"name": "小明", "age": 18, "grade": "A"}
for key, value in student.items():
print(f"{key}: {value}")
# 遍历字符串
for char in "Python":
print(char)
# enumerate()——同时获取索引和值
colors = ["红", "黄", "蓝"]
for index, color in enumerate(colors):
print(f"第{index + 1}个颜色是:{color}")
while循环——条件满足时重复执行
# 基础while循环
count = 0
while count < 5:
print(f"计数:{count}")
count += 1 # 别忘了更新条件,否则会死循环!
# break——提前退出循环
while True:
user_input = input("输入'退出'结束程序:")
if user_input == "退出":
break
print(f"你输入了:{user_input}")
# continue——跳过本次循环
for num in range(1, 11):
if num % 2 == 0:
continue # 跳过偶数
print(num) # 只打印奇数:1, 3, 5, 7, 9
第五步:函数——把重复的代码包装起来
函数是Python编程的核心概念。一个好的函数应该只做一件事,并且尽量做到可复用。
定义和调用函数
# 最简单的函数
def greet():
print("你好!")
greet() # 调用函数
# 带参数的函数
def greet_person(name):
print(f"你好,{name}!")
greet_person("张三") # 你好,张三!
greet_person("李四") # 你好,李四!
# 带返回值的函数
def add(a, b):
return a + b
result = add(3, 5)
print(f"3 + 5 = {result}") # 3 + 5 = 8
# 默认参数
def calculate_area(length, width=10):
"""计算矩形面积,宽度默认为10"""
return length * width
print(calculate_area(5)) # 50(用默认宽度10)
print(calculate_area(5, 8)) # 40(自定义宽度)
参数传递的高级技巧
# 关键字参数——调用时指定参数名
def create_user(name, age, email, phone):
return {
"name": name,
"age": age,
"email": email,
"phone": phone
}
# 两种方式效果一样
user1 = create_user("小明", 18, "xm@example.com", "13800138000")
user2 = create_user(name="小明", age=18, email="xm@example.com", phone="13800138000")
user3 = create_user("小明", 18, phone="13800138000", email="xm@example.com") # 顺序可以打乱
# *args——接收任意数量的位置参数(打包成元组)
def sum_all(*args):
total = 0
for num in args:
total += num
return total
print(sum_all(1, 2, 3)) # 6
print(sum_all(1, 2, 3, 4, 5)) # 15
# **kwargs——接收任意数量的关键字参数(打包成字典)
def build_profile(**kwargs):
return kwargs
profile = build_profile(name="小明", age=18, city="北京")
print(profile) # {'name': '小明', 'age': 18, 'city': '北京'}
# 同时使用 *args 和 **kwargs
def flexible_func(*args, **kwargs):
print(f"位置参数:{args}")
print(f"关键字参数:{kwargs}")
flexible_func(1, 2, 3, name="小明", age=18)
lambda函数——匿名函数的快捷方式
# 普通函数
def square(x):
return x * x
# 等价于lambda表达式
square = lambda x: x * x
print(square(5)) # 25
# lambda常用场景:配合map、filter、sorted使用
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# map——对每个元素应用函数
squared = list(map(lambda x: x**2, numbers))
print(squared) # [9, 1, 16, 1, 25, 81, 4, 36]
# filter——过滤元素
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [4, 2, 6]
# sorted——自定义排序规则
students = [
{"name": "小明", "score": 85},
{"name": "小红", "score": 92},
{"name": "小刚", "score": 78},
]
# 按分数从高到低排序
sorted_students = sorted(students, key=lambda s: s["score"], reverse=True)
for s in sorted_students:
print(f"{s['name']}: {s['score']}分")
第六步:文件操作——让程序学会读写文件
真实项目里,程序几乎一定会和文件打交道。
读写文本文件
# 写入文件(覆盖模式)
with open("日记.txt", "w", encoding="utf-8") as f:
f.write("今天是学习Python的第一天。\n")
f.write("感觉Python比想象中简单多了!\n")
# 追加写入
with open("日记.txt", "a", encoding="utf-8") as f:
f.write("明天要继续加油!\n")
# 读取文件
with open("日记.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# 逐行读取
with open("日记.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip()) # strip()去掉行末的换行符
# 读取所有行到列表
with open("日记.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
print(lines) # ['今天是学习Python的第一天。\n', '感觉Python比想象中简单多了!\n', ...]
为什么要用 with 语句? with 语句会在代码块执行完毕后自动关闭文件,即使中间出错了也会关闭。这是一个非常重要的好习惯,能避免文件资源泄漏。
读写JSON文件——项目中最常用的数据格式
import json
# 写入JSON文件
data = {
"name": "小明",
"age": 18,
"hobbies": ["编程", "阅读", "跑步"],
"scores": {"math": 95, "english": 88, "python": 100}
}
with open("student.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
# ensure_ascii=False 保证中文正常显示
# indent=4 让JSON格式美观(缩进4个空格)
# 读取JSON文件
with open("student.json", "r", encoding="utf-8") as f:
student = json.load(f)
print(student["name"]) # 小明
print(student["scores"]["python"]) # 100
# 修改数据并保存
student["age"] = 19
student["scores"]["python"] = 100
with open("student.json", "w", encoding="utf-8") as f:
json.dump(student, f, ensure_ascii=False, indent=4)
读写CSV文件——处理表格数据
import csv
# 写入CSV
students = [
["姓名", "年龄", "分数"],
["小明", 18, 95],
["小红", 17, 88],
["小刚", 19, 92]
]
with open("students.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerows(students)
# 读取CSV
with open("students.csv", "r", encoding="utf-8", newline="") as f:
reader = csv.reader(f)
for row in reader:
print(row)
# 用字典方式读取CSV(更方便)
with open("students.csv", "r", encoding="utf-8", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['姓名']} 分数:{row['分数']}")
第七步:面向对象编程——用代码建模现实世界
很多初学者觉得OOP(面向对象编程)很难,但其实你只要记住一件事:程序是用来描述和模拟现实世界的。
类和对象的基本概念
class Dog:
# 类属性——所有对象共享
species = "犬科动物"
# 构造函数——创建对象时自动调用
def __init__(self, name, age, breed):
# 实例属性——每个对象各自独立
self.name = name
self.age = age
self.breed = breed
# 实例方法
def bark(self):
return f"{self.name}在叫:汪汪汪!🐕"
def get_human_age(self):
"""狗年龄换算成人年龄(粗略估算)"""
return self.age * 7
def __str__(self):
"""定义对象的字符串表示"""
return f"Dog({self.name}, {self.age}岁, {self.breed})"
# 创建对象
dog1 = Dog("旺财", 3, "金毛")
dog2 = Dog("豆豆", 5, "哈士奇")
print(dog1.name) # 旺财
print(dog1.bark()) # 旺财在叫:汪汪汪!
print(dog1.get_human_age()) # 21
print(dog2) # Dog(豆豆, 5岁, 哈士奇)
封装——保护数据不被乱改
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.__balance = balance # 双下划线开头=私有属性,外部不能直接访问
def deposit(self, amount):
"""存款"""
if amount > 0:
self.__balance += amount
return True
return False
def withdraw(self, amount):
"""取款"""
if 0 < amount <= self.__balance:
self.__balance -= amount
return True
return False
def get_balance(self):
"""查询余额(提供受控的访问方式)"""
return self.__balance
# 使用
account = BankAccount("小明", 1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance()) # 1300
# print(account.__balance) # 这会报错!无法直接访问私有属性
继承——代码复用神器
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
return "..."
def info(self):
return f"{self.name},{self.age}岁"
# 继承Animal
class Dog(Animal):
def speak(self):
return "汪汪汪!"
def fetch(self, item):
return f"{self.name}去拿{item}了 🐕"
# 继承Animal
class Cat(Animal):
def speak(self):
return "喵喵喵~"
def climb(self):
return f"{self.name}爬上树了 🐈"
# 使用
dog = Dog("旺财", 3)
cat = Cat("咪咪", 2)
print(dog.info()) # 旺财,3岁
print(dog.speak()) # 汪汪汪!
print(dog.fetch("球")) # 旺财去拿球了
print(cat.speak()) # 喵喵喵~
第八步:错误处理——让程序更健壮
写代码出bug是常态,优秀的程序员不是不出错,而是懂得如何优雅地处理错误。
# 基础try-except结构
try:
result = 10 / 0
except ZeroDivisionError:
print("哎呀,不能除以零!")
# 捕获多种异常
try:
age = int(input("请输入你的年龄:"))
result = 100 / age
except ValueError:
print("请输入一个有效的数字!")
except ZeroDivisionError:
print("年龄不能为零!")
except Exception as e:
print(f"发生了未知错误:{e}")
else:
print(f"计算结果:{result}") # 只有在没有异常时才执行
finally:
print("这段代码无论如何都会执行")
# 自定义异常
class AgeError(Exception):
"""自定义异常:年龄不合法"""
def __init__(self, age, message="年龄必须在0-150之间"):
self.age = age
self.message = message
super().__init__(self.message)
def check_age(age):
if not (0 <= age <= 150):
raise AgeError(age)
return True
try:
check_age(200)
except AgeError as e:
print(f"年龄错误:{e.age}岁,{e.message}")
第九步:模块和包——站在巨人的肩膀上
Python最强大的地方在于它的生态。别人已经写好了解决各种问题的代码,你只需要拿来用就行。
导入模块的几种方式
# 导入整个模块
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
# 导入模块中的特定函数
from math import sqrt, pi
print(sqrt(25)) # 5.0
print(pi) # 3.141592653589793
# 给模块起别名
import numpy as np
import pandas as pd
# 导入模块中的所有(不推荐,但有时候方便)
from os import *
2024年最常用的第三方库
# ──────────────────────────────────────
# 1. requests —— 发送网络请求
# ──────────────────────────────────────
# 安装:pip install requests
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # 200
print(response.json()) # 返回的JSON数据
# ──────────────────────────────────────
# 2. pandas —— 数据处理和分析
# ──────────────────────────────────────
# 安装:pip install pandas
import pandas as pd
# 创建DataFrame
df = pd.DataFrame({
"姓名": ["小明", "小红", "小刚"],
"年龄": [18, 17, 19],
"分数": [95, 88, 92]
})
print(df)
print(df["分数"].mean()) # 91.666...
# ──────────────────────────────────────
# 3. datetime —— 日期时间处理
# ──────────────────────────────────────
from datetime import datetime, timedelta
now = datetime.now()
print(now) # 2024-01-15 14:30:00.123456
print(now.strftime("%Y-%m-%d")) # 2024-01-15
tomorrow = now + timedelta(days=1)
print(tomorrow.strftime("%Y年%m月%d日")) # 2024年01月16日
# ──────────────────────────────────────
# 4. pathlib —— 现代文件路径操作(2024年强烈推荐)
# ──────────────────────────────────────
from pathlib import Path
# 创建路径对象
p = Path("documents/reports/2024/report.pdf")
print(p.name) # report.pdf
print(p.suffix) # .pdf
print(p.stem) # report
print(p.parent) # documents/reports/2024
print(p.exists()) # False(文件不存在)
# 创建目录和文件
Path("test_dir").mkdir(exist_ok=True)
(Path("test_dir") / "hello.txt").write_text("Hello, 2024!")
第十步:实战项目——做一个真正能用的程序
学完前面的知识,我们来做一个完整的实战项目:个人记账本。这个项目涵盖了变量、函数、文件操作、面向对象、错误处理等所有核心概念。
"""
个人记账本 v1.0
功能:记录收支、查询统计、数据持久化
作者:一个正在学Python的你
"""
import json
from pathlib import Path
from datetime import datetime
from typing import Optional
# ──────────────────────────────────────
# 数据层——负责读写文件
# ──────────────────────────────────────
DATA_FILE = Path("expenses.json")
def load_data() -> dict:
"""从JSON文件加载数据"""
if DATA_FILE.exists():
with open(DATA_FILE, "r", encoding="utf-8") as f:
return json.load(f)
return {"records": [], "categories": ["餐饮", "交通", "购物", "娱乐", "医疗", "其他"]}
def save_data(data: dict) -> None:
"""保存数据到JSON文件"""
with open(DATA_FILE, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# ──────────────────────────────────────
# 业务逻辑层——处理记账相关操作
# ──────────────────────────────────────
class ExpenseTracker:
def __init__(self):
self.data = load_data()
def add_expense(self, amount: float, category: str, note: str = "") -> bool:
"""添加一笔支出"""
# 验证金额
if amount <= 0:
print("❌ 金额必须是正数!")
return False
# 验证分类
if category not in self.data["categories"]:
print(f"❌ 无效分类,可用分类:{', '.join(self.data['categories'])}")
return False
# 创建记录
record = {
"id": len(self.data["records"]) + 1,
"date": datetime.now().strftime("%Y-%m-%d %H:%M"),
"amount": round(amount, 2),
"category": category,
"note": note
}
self.data["records"].append(record)
save_data(self.data)
print(f"✅ 已记录:{category} - {amount}元")
return True
def show_records(self, limit: int = 10) -> None:
"""显示最近的记录"""
records = self.data["records"]
if not records:
print("📭 暂无记录,来记一笔吧!")
return
print(f"\n📋 最近 {min(limit, len(records))} 条记录:")
print("-" * 50)
for r in records[-limit:]:
note_str = f" — {r['note']}" if r.get("note") else ""
print(f"{r['date']} | {r['category']:6} | {r['amount']:>6.2f}元{note_str}")
print("-" * 50)
def show_summary(self) -> None:
"""显示收支统计"""
records = self.data["records"]
if not records:
print("📭 暂无数据,无法统计")
return
# 按分类统计
category_stats = {}
total = 0
for r in records:
cat = r["category"]
amount = r["amount"]
category_stats[cat] = category_stats.get(cat, 0) + amount
total += amount
print(f"\n💰 总消费:{total:.2f}元")
print("📊 分类明细:")
print("-" * 30)
# 按金额从高到低排序
sorted_stats = sorted(category_stats.items(), key=lambda x: x[1], reverse=True)
for cat, amt in sorted_stats:
pct = (amt / total) * 100
bar = "█" * int(pct / 5) # 简单进度条
print(f" {cat:6} | {amt:>7.2f}元 ({pct:5.1f}%) {bar}")
def search(self, keyword: str) -> None:
"""搜索记录"""
records = self.data["records"]
matches = [r for r in records if
keyword.lower() in r["category"].lower() or
keyword.lower() in r.get("note", "").lower()]
if not matches:
print(f"🔍 未找到包含「{keyword}」的记录")
return
print(f"\n🔍 找到 {len(matches)} 条相关记录:")
print("-" * 50)
for r in matches:
note_str = f" — {r['note']}" if r.get("note") else ""
print(f"{r['date']} | {r['category']:6} | {r['amount']:>6.2f}元{note_str}")
# ──────────────────────────────────────
# 交互层——命令行界面
# ──────────────────────────────────────
def print_menu():
print("\n" + "=" * 40)
print(" 📒 个人记账本")
print("=" * 40)
print(" 1. 添加支出")
print(" 2. 查看记录")
print(" 3. 统计汇总")
print(" 4. 搜索记录")
print(" 5. 退出")
print("=" * 40)
def main():
tracker = ExpenseTracker()
print("👋 欢迎使用个人记账本!")
print("💡 提示:数据保存在 expenses.json 文件中")
while True:
print_menu()
choice = input("请选择操作(1-5):").strip()
if choice == "1":
try:
amount = float(input("金额:"))
print(f"可用分类:{', '.join(tracker.data['categories'])}")
category = input("分类:").strip()
note = input("备注(可选,直接回车跳过):").strip()
tracker.add_expense(amount, category, note)
except ValueError:
print("❌ 金额请输入数字!")
elif choice == "2":
tracker.show_records()
elif choice == "3":
tracker.show_summary()
elif choice == "4":
keyword = input("请输入搜索关键词:").strip()
tracker.search(keyword)
elif choice == "5":
print("👋 再见!感谢使用记账本~")
break
else:
print("❌ 无效选择,请重新输入")
if __name__ == "__main__":
main()
运行这个程序后,你会得到一个可以真正使用的记账工具,数据会保存在 expenses.json 文件中,关闭程序再打开,数据还在。
第十一步:进阶方向——下一步往哪儿走
完成上面的项目后,你已经掌握了Python最核心的知识。接下来可以根据自己的兴趣选择方向:
方向一:数据分析
# 推荐库:pandas, numpy, matplotlib, seaborn
import pandas as pd
import matplotlib.pyplot as plt
# 读取Excel数据
df = pd.read_excel("sales_data.xlsx")
# 数据分析
print(df.describe())
# 可视化
df.groupby("月份")["销售额"].sum().plot(kind="bar")
plt.title("月度销售额")
plt.show()
方向二:Web开发
# 推荐框架:Flask(轻量)、FastAPI(现代、高性能)
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/")
def hello():
return jsonify({"message": "Hello, Python!"})
@app.route("/api/users/<int:user_id>")
def get_user(user_id):
return jsonify({"id": user_id, "name": "小明"})
if __name__ == "__main__":
app.run(debug=True)
方向三:自动化办公
# 推荐库:openpyxl(Excel), python-docx(Word), pyautogui(自动化)
import openpyxl
# 批量处理Excel
wb = openpyxl.load_workbook("report.xlsx")
sheet = wb.active
for row in sheet.iter_rows(min_row=2):
for cell in row:
if cell.value and isinstance(cell.value, (int, float)):
cell.value = round(cell.value, 2)
wb.save("report_cleaned.xlsx")
print("✅ 数据已整理完成")
方向四:人工智能/机器学习
# 推荐库:torch(PyTorch), tensorflow, scikit-learn
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
# 加载数据
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.3, random_state=42
)
# 训练模型
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
# 评估
predictions = model.predict(X_test)
print(f"准确率:{accuracy_score(y_test, predictions):.2%}")
给初学者的一些真心话
不要追求完美,先追求完成。 很多人卡在”还没准备好”的状态,迟迟不写第一行代码。记住:写出能跑的代码,比写出完美的代码重要一万倍。
遇到问题先搜索,再提问。 99%的问题别人都遇到过,Stack Overflow 和 GitHub Issues 是最好的老师。搜索时加上 “Python 3” 和具体的错误信息,能找到更精准的答案。
保持动手。 看十遍教程不如自己动手写一遍。每学一个概念,都写个小例子试试,哪怕只是打印个 Hello World。
加入社区。 GitHub、知乎、V2EX、CSDN、Reddit的r/learnpython,都是好地方。看到别人写代码、解决问题,进步会非常快。
Python的世界很大,但起点很小。你现在看到的每一个概念,都是无数开发者踩过的坑总结出来的。别怕犯错,别怕问”傻问题”,你的第一行代码就是你成为程序员的起点。
加油!🐍
