本文目录导读:

“经典”的 Python 案例通常具备以下特征:
- 覆盖核心语法:包含变量、循环、条件、函数、列表/字典操作等
- 包含常用数据结构:如列表、元组、集合、字典等
- 体现Python特色:如列表推导式、切片、生成器、装饰器等
- 具有实际应用场景:能解决真实的问题
- 难度适中:太简单无趣,太难不适合自学
以下按难度分级,整理一些经典案例:
入门级经典案例
1 猜数字游戏
import random
target = random.randint(1, 100)
guess = None
while guess != target:
guess = int(input("猜一个1-100的数字:"))
if guess > target:
print("太大了!")
elif guess < target:
print("太小了!")
else:
print("恭喜你猜对了!")
价值:覆盖while循环、条件判断、输入输出、随机数
2 水仙花数
找出100-999之间的水仙花数(各位数字的立方和等于该数本身)
for num in range(100, 1000):
a = num // 100
b = (num // 10) % 10
c = num % 10
if a**3 + b**3 + c**3 == num:
print(num)
价值:数字分解操作、循环、条件判断
进阶级经典案例
1 斐波那契数列
生成斐波那契数列(多种实现方式)
# 方式1:递归(经典但效率低)
def fib_recursive(n):
return n if n <= 1 else fib_recursive(n-1) + fib_recursive(n-2)
# 方式2:迭代(推荐)
def fib_iterative(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
# 方式3:生成器
def fib_generator():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
# 使用
for i, num in enumerate(fib_generator()):
if i > 10:
break
print(num)
价值:递归 vs 迭代、生成器、元组解包
2 验证回文串
def is_palindrome(s):
# 经典写法
s = ''.join(c.lower() for c in s if c.isalnum())
return s == s[::-1]
# 测试
print(is_palindrome("A man, a plan, a canal: Panama")) # True
价值:字符串切片[::-1]、列表推导式、字符串方法
3 统计词频
from collections import Counter
import re
text = "Python is great. Python is powerful. Python is fun."
# 方法1:用字典
words = re.findall(r'\w+', text.lower())
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
# 方法2:用Counter
freq = Counter(re.findall(r'\w+', text.lower()))
# 排序输出
for word, count in freq.most_common(3):
print(f"{word}: {count}")
价值:字典操作、Counter、正则表达式
高级经典案例
1 装饰器:计算函数执行时间
import time
from functools import wraps
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} 执行耗时:{end-start:.4f}秒")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return "完成"
print(slow_function())
价值:装饰器、闭包、functools.wraps
2 上下文管理器(with语句)
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
# 使用
with FileManager('test.txt', 'w') as f:
f.write('Hello, World!')
价值:面向对象、上下文管理协议
实战型经典案例
1 简易爬虫(网页标题抓取)
import requests
from bs4 import BeautifulSoup
def get_title(url):
try:
response = requests.get(url, timeout=5)
soup = BeautifulSoup(response.text, 'html.parser')
return soup.title.string.strip()
except Exception as e:
return f"错误:{e}"
# 使用
urls = ['https://www.python.org', 'https://www.github.com']
for url in urls:
print(f"{url} 的标题是:{get_title(url)}")
价值:第三方库使用、异常处理、实际应用场景
2 学生成绩管理系统
class Student:
def __init__(self, name, scores):
self.name = name
self.scores = scores
@property
def average(self):
return sum(self.scores) / len(self.scores)
@property
def grade(self):
avg = self.average
if avg >= 90: return 'A'
elif avg >= 80: return 'B'
elif avg >= 70: return 'C'
elif avg >= 60: return 'D'
else: return 'F'
# 使用
students = [
Student("张三", [85, 92, 78]),
Student("李四", [60, 65, 70]),
Student("王五", [95, 98, 99])
]
sorted_students = sorted(students, key=lambda s: s.average, reverse=True)
for s in sorted_students:
print(f"{s.name}: 平均分 {s.average:.1f}, 等级 {s.grade}")
价值:面向对象、@property装饰器、lambda函数、排序
权威来源中的经典案例
以下资源中包含了大量公认的经典案例:
- Python官方文档的"Tutorial"部分
- LeetCode上的Python题目(特别是easy和medium难度)
- Python Cookbook(《Python Cookbook中文版》)
- Automate the Boring Stuff with Python(《Python编程快速上手》)
- Dive Into Python(《深入Python》)
选择案例的建议
- 先掌握基础(猜数字、水仙花数)
- 再玩数据结构和算法(回文、排序、搜索)
- 最后上手实战(爬虫、数据处理、Web应用)
真正好的案例不是看它有多复杂,而是:
- 你动手写了多少代码
- 你理解了背后的原理
- 你能举一反三,应用到其他场景
你觉得哪个案例比较适合你现在的水平?我可以进一步帮你拆解和分析。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播