100个python代码大全

1. **Hello World:**
   ```python
   print("Hello, World!")
   ```

2. **变量和数据类型:**
   ```python
   name = "John"
   age = 25
   height = 1.75
   is_student = False
   ```

3. **条件语句:**
   ```python
   if age >= 18:
       print("You are an adult.")
   else:
       print("You are a minor.")
   ```

4. **循环:**
   ```python
   for i in range(5):
       print(i)
   ```

5. **函数:**
   ```python
   def greet(name):
       print("Hello, " + name + "!")
       
   greet("Alice")
   ```

6. **列表和循环:**
   ```python
   numbers = [1, 2, 3, 4, 5]
   for num in numbers:
       print(num)
   ```

7. **文件读写:**
   ```python
   with open("example.txt", "w") as file:
       file.write("Hello, File!")

   with open("example.txt", "r") as file:
       content = file.read()
       print(content)
   ```

8. **异常处理:**
   ```python
   try:
       result = 10 / 0
   except ZeroDivisionError:
       print("Cannot divide by zero.")
   ```

9. **字典:**
   ```python
   person = {"name": "Alice", "age": 30, "city": "Wonderland"}
   print(person["name"])
   ```

10. **日期和时间:**
    ```python
    from datetime import datetime

    current_time = datetime.now()
    print(current_time)
    ```

11. **正则表达式:**
    ```python
    import re

    text = "The price is $20."
    match = re.search(r'\$(\d+)', text)
    if match:
        print("Price:", match.group(1))
    ```

12. **JSON 解析:**
    ```python
    import json

    data = '{"name": "Bob", "age": 25}'
    parsed_data = json.loads(data)
    print(parsed_data["name"])
    ```

13. **爬虫基础:**
    ```python
    import requests

    response = requests.get("https://www.example.com")
    print(response.text)
    ```

14. **多线程:**
    ```python
    import threading
    import time

    def print_numbers():
        for i in range(5):
            time.sleep(1)
            print(i)

    thread = threading.Thread(target=print_numbers)
    thread.start()
    ```

15. **GUI 界面:**
    ```python
    from tkinter import Tk, Label

    root = Tk()
    label = Label(root, text="Hello, GUI!")
    label.pack()
    root.mainloop()
    ```

16. **类和对象:**
    ```python
    class Dog:
        def __init__(self, name, age):
            self.name = name
            self.age = age

        def bark(self):
            print("Woof!")

    my_dog = Dog("Buddy", 3)
    print(my_dog.name)
    my_dog.bark()
    ```

17. **Lambda 表达式:**
    ```python
    square = lambda x: x ** 2
    print(square(5))
    ```

18. **Map 和 Filter:**
    ```python
    numbers = [1, 2, 3, 4, 5]
    squared_numbers = list(map(lambda x: x**2, numbers))
    even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

    print(squared_numbers)
    print(even_numbers)
    ```

19. **列表推导式:**
    ```python
    squares = [x**2 for x in range(5)]
    even_squares = [x**2 for x in range(5) if x % 2 == 0]

    print(squares)
    print(even_squares)
    ```

20. **使用 Pillow 处理图像:**
    ```python
    from PIL import Image

    img = Image.open("image.jpg")
    img.show()
    ```

21. **NumPy 数组操作:**
    ```python
    import numpy as np

    array = np.array([[1, 2, 3], [4, 5, 6]])
    transposed = np.transpose(array)

    print(array)
    print(transposed)
    ```

22. **Pandas 数据分析:**
    ```python
    import pandas as pd

    data = {'Name': ['Alice', 'Bob', 'Charlie'],
            'Age': [25, 30, 22]}
    df = pd.DataFrame(data)

    print(df)
    ```

23. **Matplotlib 绘图:**
    ```python
    import matplotlib.pyplot as plt

    x = [1, 2, 3, 4, 5]
    y = [2, 4, 6, 8, 10]

    plt.plot(x, y)
    plt.xlabel('X-axis')
    plt.ylabel('Y-axis')
    plt.title('Simple Plot')
    plt.show()
    ```

24. **使用 Flask 构建 Web 应用:**
    ```python
    from flask import Flask

    app = Flask(__name__)

    @app.route('/')
    def hello():
        return 'Hello, Flask!'

    if __name__ == '__main__':
        app.run(debug=True)
    ```

25. **使用 SQLAlchemy 进行数据库操作:**
    ```python
    from sqlalchemy import create_engine, Column, Integer, String
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker

    engine = create_engine('sqlite:///example.db', echo=True)
    Base = declarative_base()

    class User(Base):
        __tablename__ = 'users'

        id = Column(Integer, primary_key=True)
        name = Column(String)
        age = Column(Integer)

    Base.metadata.create_all(engine)

    # 使用 session 进行数据库操作
    ```

26. **使用 Flask 实现 RESTful API:**
    ```python
    from flask import Flask, jsonify

    app = Flask(__name__)

    @app.route('/api/greet/', methods=['GET'])
    def greet(name):
        message = {'greeting': f'Hello, {name}!'}
        return jsonify(message)

    if __name__ == '__main__':
        app.run(debug=True)
    ```

27. **异步编程 with Asyncio:**
    ```python
    import asyncio

    async def hello():
        print("Hello, ")
        await asyncio.sleep(1)
        print("Async World!")

    asyncio.run(hello())
    ```

28. **发送电子邮件:**
    ```python
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart

    sender_email = "[email protected]"
    receiver_email = "[email protected]"
    password = "your_email_password"

    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = receiver_email
    message['Subject'] = "Test Email"

    body = "This is a test email."
    message.attach(MIMEText(body, 'plain'))

    with smtplib.SMTP('smtp.gmail.com', 587) as server:
        server.starttls()
        server.login(sender_email, password)
        server.send_message(message)
    ```

29. **使用 Flask 进行用户认证:**
    ```python
    from flask import Flask, request, jsonify
    from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity

    app = Flask(__name__)
    app.config['JWT_SECRET_KEY'] = 'super-secret'  # Change this in a real application
    jwt = JWTManager(app)

    @app.route('/login', methods=['POST'])
    def login():
        username = request.json.get('username', None)
        password = request.json.get('password', None)

        if username != 'user' or password != 'pass':
            return jsonify({"msg": "Bad username or password"}), 401

        access_token = create_access_token(identity=username)
        return jsonify(access_token=access_token), 200

    @app.route('/protected', methods=['GET'])
    @jwt_required()
    def protected():
        current_user = get_jwt_identity()
        return jsonify(logged_in_as=current_user), 200

    if __name__ == '__main__':
        app.run(debug=True)
    ```

30. **使用 TensorFlow 进行简单的机器学习:**
    ```python
    import tensorflow as tf
    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Dense

    # Create a simple model
    model = Sequential([
        Dense(10, activation='relu', input_shape=(784,)),
        Dense(10, activation='softmax')
    ])

    model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
    ```

31. **使用 OpenCV 处理图像:**
    ```python
    import cv2

    # 读取图像
    image = cv2.imread('image.jpg')

    # 将图像转换为灰度
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 显示图像
    cv2.imshow('Original Image', image)
    cv2.imshow('Gray Image', gray_image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    ```

32. **使用 Selenium 进行 Web 自动化:**
    ```python
    from selenium import webdriver

    driver = webdriver.Chrome()

    # 打开网页
    driver.get('https://www.example.com')

    # 查找元素并操作
    search_box = driver.find_element('name', 'q')
    search_box.send_keys('Python')
    search_box.submit()

    # 关闭浏览器
    driver.quit()
    ```

33. **使用 Pytest 进行单元测试:**
    ```python
    def add(a, b):
        return a + b

    def test_add():
        assert add(2, 3) == 5
        assert add(-1, 1) == 0
        assert add(0, 0) == 0
    ```

34. **使用 Requests 发送 HTTP 请求:**
    ```python
    import requests

    response = requests.get('https://www.example.com')
    print(response.status_code)
    print(response.text)
    ```

35. **使用 Flask-WTF 创建表单:**
    ```python
    from flask import Flask, render_template
    from flask_wtf import FlaskForm
    from wtforms import StringField, SubmitField

    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret_key'

    class MyForm(FlaskForm):
        name = StringField('Name')
        submit = SubmitField('Submit')

    @app.route('/', methods=['GET', 'POST'])
    def index():
        form = MyForm()

        if form.validate_on_submit():
            return f'Hello, {form.name.data}!'

        return render_template('index.html', form=form)

    if __name__ == '__main__':
        app.run(debug=True)
    ```

36. **使用 Flask-SocketIO 实现实时通信:**
    ```python
    from flask import Flask, render_template
    from flask_socketio import SocketIO

    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret_key'
    socketio = SocketIO(app)

    @app.route('/')
    def index():
        return render_template('index.html')

    @socketio.on('message')
    def handle_message(msg):
        print('Message:', msg)
        socketio.emit('message', msg)

    if __name__ == '__main__':
        socketio.run(app, debug=True)
    ```

37. **使用 Flask-RESTful 创建 RESTful API:**
    ```python
    from flask import Flask
    from flask_restful import Resource, Api

    app = Flask(__name__)
    api = Api(app)

    class HelloWorld(Resource):
        def get(self):
            return {'hello': 'world'}

    api.add_resource(HelloWorld, '/')

    if __name__ == '__main__':
        app.run(debug=True)
    ```

38. **使用 Flask-Migrate 进行数据库迁移:**
    ```python
    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    from flask_migrate import Migrate

    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
    db = SQLAlchemy(app)
    migrate = Migrate(app, db)

    class User(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        username = db.Column(db.String(80), unique=True, nullable=False)

    @app.route('/')
    def index():
        users = User.query.all()
        return ', '.join([user.username for user in users])

    if __name__ == '__main__':
        app.run(debug=True)
    ```

39. **使用 FastAPI 创建现代 Web API:**
    ```python
    from fastapi import FastAPI

    app = FastAPI()

    @app.get("/")
    def read_root():
        return {"Hello": "World"}

    @app.get("/items/{item_id}")
    def read_item(item_id: int, query_param: str = None):
        return {"item_id": item_id, "query_param": query_param}
    ```

40. **使用 Flask-Login 进行用户认证:**
    ```python
    from flask import Flask, render_template, redirect, url_for
    from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user

    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret_key'
    login_manager = LoginManager(app)

    class User(UserMixin):
        def __init__(self, user_id):
            self.id = user_id

    @login_manager.user_loader
    def load_user(user_id):
        return User(user_id)

    @app.route('/login/')
    def login(user_id):
        user = User(user_id)
        login_user(user)
        return redirect(url_for('protected'))

    @app.route('/protected')
    @login_required
    def protected():
        return f'Hello, {current_user.id}!'

    @app.route('/logout')
    @login_required
    def logout():
        logout_user()
        return 'Logged out successfully.'

    if __name__ == '__main__':
        app.run(debug=True)
    ```

41. **使用 PyTorch 进行简单的深度学习:**
    ```python
    import torch
    import torch.nn as nn
    import torch.optim as optim

    # 定义一个简单的神经网络
    class SimpleNet(nn.Module):
        def __init__(self):
            super(SimpleNet, self).__init__()
            self.fc = nn.Linear(10, 1)

        def forward(self, x):
            return self.fc(x)

    # 创建模型、损失函数和优化器
    model = SimpleNet()
    criterion = nn.MSELoss()
    optimizer = optim.SGD(model.parameters(), lr=0.01)

    # 训练模型
    for epoch in range(100):
        inputs = torch.randn(100, 10)  # 随机生成输入
        targets = torch.randn(100, 1)  # 随机生成目标值

        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, targets)
        loss.backward()
        optimizer.step()
    ```

42. **使用 Flask-Security 实现用户认证和授权:**
    ```python
    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin

    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret_key'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
    db = SQLAlchemy(app)

    # 定义用户和角色模型
    roles_users = db.Table('roles_users',
        db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
        db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))
    )

    class Role(db.Model, RoleMixin):
        id = db.Column(db.Integer(), primary_key=True)
        name = db.Column(db.String(80), unique=True)

    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        email = db.Column(db.String(255), unique=True)
        password = db.Column(db.String(255))
        roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'))

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)

    if __name__ == '__main__':
        app.run(debug=True)
    ```

43. **使用 Pandas 处理时间序列数据:**
    ```python
    import pandas as pd

    # 创建一个简单的时间序列
    date_rng = pd.date_range(start='2022-01-01', end='2022-01-10', freq='D')
    time_series = pd.Series(range(len(date_rng)), index=date_rng)

    # 汇总每周的数据
    weekly_sum = time_series.resample('W').sum()
    ```

44. **使用 Flask-JWT-Extended 实现 JSON Web Token (JWT) 认证:**
    ```python
    from flask import Flask
    from flask_jwt_extended import JWTManager, jwt_required, create_access_token

    app = Flask(__name__)
    app.config['JWT_SECRET_KEY'] = 'secret_key'
    jwt = JWTManager(app)

    @app.route('/login', methods=['POST'])
    def login():
        username = request.json.get('username', None)
        password = request.json.get('password', None)

        if username != 'user' or password != 'pass':
            return jsonify({"msg": "Bad username or password"}), 401

        access_token = create_access_token(identity=username)
        return jsonify(access_token=access_token), 200

    @app.route('/protected', methods=['GET'])
    @jwt_required()
    def protected():
        current_user = get_jwt_identity()
        return jsonify(logged_in_as=current_user), 200

    if __name__ == '__main__':
        app.run(debug=True)
    ```

45. **使用 Flask-RESTful 配合 SQLAlchemy 构建 RESTful API:**
    ```python
    from flask import Flask
    from flask_restful import Resource, Api, reqparse
    from flask_sqlalchemy import SQLAlchemy

    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
    db = SQLAlchemy(app)
    api = Api(app)

    # 定义数据模型
    class Todo(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        task = db.Column(db.String(120))

    # 创建请求解析器
    parser = reqparse.RequestParser()
    parser.add_argument('task')

    class TodoResource(Resource):
        def get(self, todo_id):
            todo = Todo.query.filter_by(id=todo_id).first()
            return {'task': todo.task}

        def put(self, todo_id):
            args = parser.parse_args()
            todo = Todo.query.filter_by(id=todo_id).first()
            todo.task = args['task']
            db.session.commit()
            return {'task': todo.task}

        def delete(self, todo_id):
            todo = Todo.query.filter_by(id=todo_id).first()
            db.session.delete(todo)
            db.session.commit()
            return {'result': True}

    api.add_resource(TodoResource, '/todos/')

    if __name__ == '__main__':
        db.create_all()
        app.run(debug=True)
    ```

46. **使用 Flask-SocketIO 实现实时多人聊天室:**
    ```python
    from flask import Flask, render_template
    from flask_socketio import SocketIO, emit

    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret_key'
    socketio = SocketIO(app)

    @app.route('/')
    def index():
        return render_template('chat.html')

    @socketio.on('message')
    def handle_message(msg):
        emit('message', msg, broadcast=True)

    if __name__ == '__main__':
        socketio.run(app, debug=True)
    ```

47. **使用 Flask-Caching 进行缓存:**
    ```python
    from flask import Flask
    from flask_caching import Cache

    app = Flask(__name__)
    cache = Cache(app, config={'CACHE_TYPE': 'simple'})

    @app.route('/')
    @cache.cached(timeout=60)
    def cached_route():
        return 'This route is cached for 60 seconds.'

    if __name__ == '__main__':
        app.run(debug=True)
    ```

48. **使用 Flask-Moment 处理日期和时间:**
    ```python
    from flask import Flask, render_template
    from flask_moment import Moment

    app = Flask(__name__)
    moment = Moment(app)

    @app.route('/')
    def index():
        return render_template('index.html')

    if __name__ == '__main__':
        app.run(debug=True)
    ```

49. **使用 Flask-RESTful 配合 Marshmallow 进行数据序列化:**
    ```python
    from flask import Flask
    from flask_restful import Resource, Api
    from flask_marshmallow import Marshmallow

    app = Flask(__name__)
    api = Api(app)
    ma = Marshmallow(app)

    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age

    class PersonSchema(ma.Schema):
        class Meta:
            fields = ('name', 'age')

    person_schema = PersonSchema()

    class PersonResource(Resource):
        def get(self, name):
            person = Person(name=name, age=30)
            return person_schema.dump(person)

    api.add_resource(PersonResource, '/person/')

    if __name__ == '__main__':
        app.run(debug=True)
    ```

50. **使用 Flask-Migrate 和 Flask-Script 进行数据库迁移和管理:**
    ```python
    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    from flask_script import Manager
    from flask_migrate import Migrate, MigrateCommand

    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
    db = SQLAlchemy(app)
    migrate = Migrate(app, db)
    manager = Manager(app)

    manager.add_command('db', MigrateCommand)

    class User(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        username = db.Column(db.String(80), unique=True, nullable=False)

    if __name__ == '__main__':
        manager.run()
    ```

这些示例覆盖了更多主题,包括实时多人聊天室(使用 Flask-SocketIO)、缓存(使用 Flask-Caching)、处理日期和时间(使用 Flask-Moment)、数据序列化(使用 Flask-RESTful 和 Marshmallow)以及数据库迁移和管理(使用 Flask-Migrate 和 Flask-Script)。

你可能感兴趣的:(python)