Python 基础示例

Python 脚本学习:15个由简入繁的实用示例

学习路径建议

  1. 初级阶段 (示例1-5): 掌握Python基础语法、流程控制、函数和数据结构
  2. 中级阶段 (示例6-10): 学习面向对象编程、异常处理、文件操作和API调用
  3. 高级阶段 (示例11-15): 掌握并发编程、装饰器、上下文管理器和综合项目开发

示例1: 基础Hello World和用户输入

# 最简单的Python程序 - 输出和输入处理
name = input("请输入你的名字: ")
print(f"你好, {name}! 欢迎学习Python!")
age = int(input("请输入你的年龄: "))
print(f"明年你将 {age + 1} 岁")

# 学习要点: 输入输出、字符串格式化、类型转换

示例2: 条件判断和循环

# 猜数字游戏 - 条件判断和循环
import random

number = random.randint(1, 100)
attempts = 0
max_attempts = 7

print("猜数字游戏! 我想了一个1到100之间的数字")

while attempts < max_attempts:
    guess = int(input("你的猜测是: "))
    attempts += 1
    
    if guess < number:
        print("太小了!")
    elif guess > number:
        print("太大了!")
    else:
        print(f"恭喜! 你在{attempts}次尝试中猜对了!")
        break
else:
    print(f"抱歉,你没有在{max_attempts}次尝试内猜对。数字是{number}")

# 学习要点: 条件语句、循环、随机数、break/else在循环中的应用

示例3: 文件操作

# 文件读写操作 - 日记程序
import datetime

def write_diary():
    entry = input("请输入今天的日记: ")
    today = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
    
    with open("diary.txt", "a", encoding="utf-8") as file:
        file.write(f"{today}\n{entry}\n\n")
    print("日记已保存!")

def read_diary():
    try:
        with open("diary.txt", "r", encoding="utf-8") as file:
            content = file.read()
            print("\n=== 我的日记 ===")
            print(content)
    except FileNotFoundError:
        print("还没有日记记录!")

# 主程序
while True:
    print("\n1. 写日记")
    print("2. 读日记")
    print("3. 退出")
    choice = input("请选择操作: ")
    
    if choice == "1":
        write_diary()
    elif choice == "2":
        read_diary()
    elif choice == "3":
        break
    else:
        print("无效选择!")

# 学习要点: 文件读写、异常处理、日期时间处理、菜单驱动程序

示例4: 函数和模块化编程

# 计算器程序 - 函数和模块化
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return "错误: 除数不能为零"
    return a / b

def calculator():
    print("简易计算器")
    print("操作: +, -, *, /")
    
    try:
        num1 = float(input("输入第一个数字: "))
        operator = input("输入操作符: ")
        num2 = float(input("输入第二个数字: "))
        
        if operator == "+":
            result = add(num1, num2)
        elif operator == "-":
            result = subtract(num1, num2)
        elif operator == "*":
            result = multiply(num1, num2)
        elif operator == "/":
            result = divide(num1, num2)
        else:
            result = "无效操作符"
        
        print(f"结果: {result}")
    except ValueError:
        print("错误: 请输入有效数字")

# 运行计算器
if __name__ == "__main__":
    calculator()

# 学习要点: 函数定义、模块化设计、错误处理、if-elif-else结构

示例5: 列表和字典操作

# 学生成绩管理系统 - 列表和字典操作
students = []

def add_student():
    name = input("输入学生姓名: ")
    grades = []
    while True:
        grade = input("输入成绩(输入'done'结束): ")
        if grade.lower() == 'done':
            break
        try:
            grades.append(float(grade))
        except ValueError:
            print("请输入有效数字!")
    
    student = {"name": name, "grades": grades, "average": sum(grades)/len(grades) if grades else 0}
    students.append(student)
    print(f"学生 {name} 已添加!")

def show_students():
    if not students:
        print("没有学生记录!")
        return
    
    print("\n=== 学生成绩表 ===")
    for student in students:
        print(f"{student['name']}: 成绩{student['grades']}, 平均分{student['average']:.2f}")

def find_top_student():
    if not students:
        print("没有学生记录!")
        return
    
    top_student = max(students, key=lambda x: x['average'])
    print(f"最高分学生: {top_student['name']}, 平均分: {top_student['average']:.2f}")

# 主程序
while True:
    print("\n1. 添加学生")
    print("2. 显示所有学生")
    print("3. 显示最高分学生")
    print("4. 退出")
    
    choice = input("请选择操作: ")
    
    if choice == "1":
        add_student()
    elif choice == "2":
        show_students()
    elif choice == "3":
        find_top_student()
    elif choice == "4":
        break
    else:
        print("无效选择!")

# 学习要点: 列表和字典操作、lambda函数、数据管理

示例6: 面向对象编程

# 银行账户系统 - 面向对象编程
class BankAccount:
    def __init__(self, account_holder, initial_balance=0):
        self.account_holder = account_holder
        self.balance = initial_balance
        self.transactions = []
    
    def deposit(self, amount):
        if amount > 0:
            self.balance += amount
            self.transactions.append(f"存款: +${amount}")
            return True
        return False
    
    def withdraw(self, amount):
        if 0 < amount <= self.balance:
            self.balance -= amount
            self.transactions.append(f"取款: -${amount}")
            return True
        return False
    
    def get_balance(self):
        return self.balance
    
    def get_transaction_history(self):
        return self.transactions

# 创建和使用账户
account = BankAccount("张三", 1000)
print(f"账户持有人: {account.account_holder}")
print(f"初始余额: ${account.get_balance()}")

account.deposit(500)
account.withdraw(200)
account.withdraw(1500)  # 这个会失败,余额不足

print(f"当前余额: ${account.get_balance()}")
print("交易记录:")
for transaction in account.get_transaction_history():
    print(transaction)

# 学习要点: 类定义、构造函数、方法、封装、对象使用

示例7: 异常处理和自定义异常

# 自定义异常和错误处理
class InsufficientFundsError(Exception):
    """自定义异常:余额不足"""
    pass

class BankAccount:
    def __init__(self, balance=0):
        self.balance = balance
    
    def withdraw(self, amount):
        if amount > self.balance:
            raise InsufficientFundsError(f"余额不足! 当前余额: ${self.balance}, 尝试取款: ${amount}")
        self.balance -= amount
        return amount

# 使用自定义异常
account = BankAccount(100)
print(f"初始余额: ${account.balance}")

try:
    account.withdraw(50)
    print(f"取款成功! 当前余额: ${account.balance}")
    
    account.withdraw(100)  # 这会引发异常
    print(f"取款成功! 当前余额: ${account.balance}")
    
except InsufficientFundsError as e:
    print(f"取款失败: {e}")
except Exception as e:
    print(f"发生未知错误: {e}")

# 学习要点: 自定义异常、异常处理、raise语句

示例8: 文件处理和CSV操作

# CSV文件处理 - 员工管理系统
import csv
import os

def add_employee():
    name = input("员工姓名: ")
    position = input("职位: ")
    salary = input("薪资: ")
    
    with open('employees.csv', 'a', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        writer.writerow([name, position, salary])
    print("员工已添加!")

def list_employees():
    if not os.path.exists('employees.csv'):
        print("没有员工记录!")
        return
    
    with open('employees.csv', 'r', encoding='utf-8') as file:
        reader = csv.reader(file)
        print("\n=== 员工列表 ===")
        for i, row in enumerate(reader, 1):
            print(f"{i}. {row[0]} - {row[1]} - ${row[2]}")

def calculate_payroll():
    if not os.path.exists('employees.csv'):
        print("没有员工记录!")
        return
    
    total_payroll = 0
    with open('employees.csv', 'r', encoding='utf-8') as file:
        reader = csv.reader(file)
        for row in reader:
            try:
                total_payroll += float(row[2])
            except ValueError:
                print(f"警告: 无效的薪资数据 '{row[2]}' 对于员工 {row[0]}")
    
    print(f"总薪资支出: ${total_payroll:.2f}")

# 主程序
while True:
    print("\n1. 添加员工")
    print("2. 列出所有员工")
    print("3. 计算总薪资")
    print("4. 退出")
    
    choice = input("请选择操作: ")
    
    if choice == "1":
        add_employee()
    elif choice == "2":
        list_employees()
    elif choice == "3":
        calculate_payroll()
    elif choice == "4":
        break
    else:
        print("无效选择!")

# 学习要点: CSV文件处理、文件存在性检查、枚举、错误处理

示例9: 正则表达式应用

# 正则表达式应用 - 数据验证和提取
import re

def validate_email(email):
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return re.match(pattern, email) is not None

def validate_phone(phone):
    pattern = r'^(\+?\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$'
    return re.match(pattern, phone) is not None

def extract_emails(text):
    pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
    return re.findall(pattern, text)

# 测试函数
test_emails = ["test@example.com", "invalid.email", "name@domain.co.uk"]
test_phones = ["123-456-7890", "(123) 456-7890", "1234567890", "invalid"]
test_text = "联系我们: support@example.com 或 sales@company.com"

print("邮箱验证:")
for email in test_emails:
    print(f"{email}: {'有效' if validate_email(email) else '无效'}")

print("\n电话验证:")
for phone in test_phones:
    print(f"{phone}: {'有效' if validate_phone(phone) else '无效'}")

print("\n提取邮箱:")
emails = extract_emails(test_text)
print(f"找到邮箱: {emails}")

# 学习要点: 正则表达式、模式匹配、数据验证、文本提取

示例10: 网络请求和API调用

# 天气查询程序 - 网络请求和API调用
import requests
import json

def get_weather(city):
    api_key = "your_api_key"  # 需要替换为实际的API密钥
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    
    params = {
        'q': city,
        'appid': api_key,
        'units': 'metric'  # 使用摄氏度
    }
    
    try:
        response = requests.get(base_url, params=params)
        response.raise_for_status()  # 如果请求失败,抛出异常
        
        data = response.json()
        
        if data['cod'] != 200:
            return f"错误: {data['message']}"
        
        weather = {
            'city': data['name'],
            'country': data['sys']['country'],
            'temperature': data['main']['temp'],
            'description': data['weather'][0]['description'],
            'humidity': data['main']['humidity'],
            'wind': data['wind']['speed']
        }
        
        return weather
        
    except requests.exceptions.RequestException as e:
        return f"网络请求错误: {e}"
    except (KeyError, IndexError) as e:
        return f"数据解析错误: {e}"

# 使用示例
city = input("请输入城市名称: ")
weather = get_weather(city)

if isinstance(weather, dict):
    print(f"\n{weather['city']}, {weather['country']} 的天气:")
    print(f"温度: {weather['temperature']}°C")
    print(f"天气: {weather['description']}")
    print(f"湿度: {weather['humidity']}%")
    print(f"风速: {weather['wind']} m/s")
else:
    print(weather)

# 学习要点: HTTP请求、API调用、JSON处理、异常处理

示例11: 多线程编程

# 多线程下载器 - 并发编程
import threading
import time
import random

def download_file(filename, size):
    """模拟文件下载"""
    print(f"开始下载 {filename} (大小: {size}MB)")
    
    for i in range(1, 11):
        time.sleep(random.uniform(0.1, 0.5))  # 模拟下载时间
        progress = i * 10
        print(f"{filename}: {progress}% 完成")
    
    print(f"{filename} 下载完成!")

# 创建多个下载任务
files = [
    ("document.pdf", 5),
    ("image.jpg", 3),
    ("video.mp4", 50),
    ("music.mp3", 8)
]

threads = []

# 创建并启动线程
for filename, size in files:
    thread = threading.Thread(target=download_file, args=(filename, size))
    threads.append(thread)
    thread.start()

# 等待所有线程完成
for thread in threads:
    thread.join()

print("所有文件下载完成!")

# 学习要点: 多线程编程、线程创建和管理、并发执行

示例12: 装饰器和函数高级特性

# 装饰器应用 - 函数计时和缓存
import time
import functools

def timer(func):
    """计算函数执行时间的装饰器"""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} 执行时间: {end_time - start_time:.4f}秒")
        return result
    return wrapper

def cache(func):
    """函数结果缓存装饰器"""
    cached_results = {}
    
    @functools.wraps(func)
    def wrapper(*args):
        if args in cached_results:
            print(f"使用缓存结果 for {args}")
            return cached_results[args]
        
        result = func(*args)
        cached_results[args] = result
        return result
    
    return wrapper

@timer
@cache
def fibonacci(n):
    """计算斐波那契数列"""
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

# 测试装饰器
print("计算斐波那契数列:")
for i in range(10):
    result = fibonacci(i)
    print(f"fib({i}) = {result}")

# 学习要点: 装饰器、函数包装、缓存、递归、函数计时

示例13: 上下文管理器

# 自定义上下文管理器 - 数据库连接模拟
class DatabaseConnection:
    def __init__(self, db_name):
        self.db_name = db_name
        self.connected = False
    
    def __enter__(self):
        """进入上下文时调用"""
        print(f"连接到数据库 {self.db_name}...")
        self.connected = True
        # 这里模拟实际的数据库连接操作
        return self
    
    def execute_query(self, query):
        """执行查询"""
        if not self.connected:
            raise Exception("未连接到数据库")
        print(f"执行查询: {query}")
        # 这里模拟查询执行和返回结果
        return f"查询 '{query}' 的结果"
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        """退出上下文时调用"""
        print("关闭数据库连接...")
        self.connected = False
        # 如果发生异常,可以在这里处理
        if exc_type:
            print(f"发生异常: {exc_val}")
        # 返回False会让异常继续传播,True会抑制异常
        return False

# 使用上下文管理器
try:
    with DatabaseConnection("my_database") as db:
        result1 = db.execute_query("SELECT * FROM users")
        print(result1)
        
        result2 = db.execute_query("SELECT * FROM products")
        print(result2)
        
        # 这里故意引发一个异常
        # raise Exception("测试异常")
except Exception as e:
    print(f"捕获到异常: {e}")

# 学习要点: 上下文管理器、with语句、资源管理、异常处理

示例14: 数据可视化

# 数据可视化 - 使用matplotlib绘制图表
import matplotlib.pyplot as plt
import numpy as np

# 创建示例数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x) * np.cos(x)

# 创建图表和子图
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 8))
fig.suptitle('三角函数可视化', fontsize=16)

# 绘制正弦函数
ax1.plot(x, y1, 'r-', label='sin(x)')
ax1.set_title('正弦函数')
ax1.set_xlabel('x')
ax1.set_ylabel('sin(x)')
ax1.legend()
ax1.grid(True)

# 绘制余弦函数
ax2.plot(x, y2, 'b--', label='cos(x)')
ax2.set_title('余弦函数')
ax2.set_xlabel('x')
ax2.set_ylabel('cos(x)')
ax2.legend()
ax2.grid(True)

# 绘制正弦余弦乘积
ax3.plot(x, y3, 'g-.', label='sin(x)*cos(x)')
ax3.set_title('正弦余弦乘积')
ax3.set_xlabel('x')
ax3.set_ylabel('sin(x)*cos(x)')
ax3.legend()
ax3.grid(True)

# 调整布局并显示图表
plt.tight_layout()
plt.savefig('trig_functions.png')  # 保存图表
plt.show()

# 学习要点: 数据可视化、matplotlib使用、子图创建、图表定制

示例15: 综合项目 - 简易博客系统

# 简易博客系统 - 综合应用
import json
import os
from datetime import datetime

class Blog:
    def __init__(self, data_file="blog_data.json"):
        self.data_file = data_file
        self.posts = self.load_posts()
    
    def load_posts(self):
        """从文件加载博客文章"""
        if os.path.exists(self.data_file):
            try:
                with open(self.data_file, 'r', encoding='utf-8') as file:
                    return json.load(file)
            except (json.JSONDecodeError, IOError):
                return []
        return []
    
    def save_posts(self):
        """保存博客文章到文件"""
        try:
            with open(self.data_file, 'w', encoding='utf-8') as file:
                json.dump(self.posts, file, ensure_ascii=False, indent=2)
            return True
        except IOError:
            return False
    
    def add_post(self, title, content, author):
        """添加新文章"""
        post = {
            'id': len(self.posts) + 1,
            'title': title,
            'content': content,
            'author': author,
            'date': datetime.now().strftime("%Y-%m-%d %H:%M"),
            'comments': []
        }
        self.posts.append(post)
        return self.save_posts()
    
    def get_posts(self):
        """获取所有文章"""
        return self.posts
    
    def get_post(self, post_id):
        """根据ID获取文章"""
        for post in self.posts:
            if post['id'] == post_id:
                return post
        return None
    
    def add_comment(self, post_id, comment, author):
        """添加评论"""
        post = self.get_post(post_id)
        if post:
            post['comments'].append({
                'author': author,
                'comment': comment,
                'date': datetime.now().strftime("%Y-%m-%d %H:%M")
            })
            return self.save_posts()
        return False

def display_posts(posts):
    """显示文章列表"""
    if not posts:
        print("暂无文章!")
        return
    
    for post in posts:
        print(f"\n[{post['id']}] {post['title']}")
        print(f"作者: {post['author']} | 日期: {post['date']}")
        print(f"内容: {post['content'][:50]}...")
        print(f"评论数: {len(post['comments'])}")

def display_post(post):
    """显示单篇文章详情"""
    if not post:
        print("文章不存在!")
        return
    
    print(f"\n标题: {post['title']}")
    print(f"作者: {post['author']} | 日期: {post['date']}")
    print(f"内容: {post['content']}")
    print("\n评论:")
    if post['comments']:
        for comment in post['comments']:
            print(f"  - {comment['author']} ({comment['date']}): {comment['comment']}")
    else:
        print("  暂无评论")

# 主程序
def main():
    blog = Blog()
    
    while True:
        print("\n=== 简易博客系统 ===")
        print("1. 查看所有文章")
        print("2. 查看文章详情")
        print("3. 发布新文章")
        print("4. 添加评论")
        print("5. 退出")
        
        choice = input("请选择操作: ")
        
        if choice == "1":
            posts = blog.get_posts()
            display_posts(posts)
        
        elif choice == "2":
            try:
                post_id = int(input("输入文章ID: "))
                post = blog.get_post(post_id)
                display_post(post)
            except ValueError:
                print("请输入有效的文章ID!")
        
        elif choice == "3":
            title = input("文章标题: ")
            content = input("文章内容: ")
            author = input("作者姓名: ")
            
            if blog.add_post(title, content, author):
                print("文章发布成功!")
            else:
                print("文章发布失败!")
        
        elif choice == "4":
            try:
                post_id = int(input("输入文章ID: "))
                comment = input("评论内容: ")
                author = input("你的姓名: ")
                
                if blog.add_comment(post_id, comment, author):
                    print("评论添加成功!")
                else:
                    print("评论添加失败!")
            except ValueError:
                print("请输入有效的文章ID!")
        
        elif choice == "5":
            print("感谢使用博客系统!")
            break
        
        else:
            print("无效选择!")

if __name__ == "__main__":
    main()

# 学习要点: 类设计、JSON数据持久化、菜单系统、数据管理、模块化编程

每个示例都展示了Python编程的不同方面,建议你逐个尝试并理解其中的概念。通过修改和扩展这些示例,你可以更深入地掌握Python编程技巧。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容