Python编程整理汇总(基础汇总版)

1. 基础语法

1.1 变量与数据类型

  • 整数:a = 10

  • 浮点数:b = 3.14

  • 字符串:c = "Hello, World!"

  • 布尔值:d = True

  • 列表:e = [1, 2, 3, 4, 5]

  • 元组:f = (1, 2, 3)

  • 字典:g = {"name": "Alice", "age": 25}

  • 集合:h = {1, 2, 3, 4, 5}

1.2 控制结构

  • if语句:if a > 5: print("a is greater than 5")

  • for循环:for i in range(5): print(i)

  • 复制代码
    while

    循环:

    复制代码
    count = 0
    while count < 5:
        print(count)
        count += 1

1.3 函数与模块

  • 函数:def greet(name): return f"Hello, {name}!"

  • 模块:

    复制代码
    # mymodule.py
    def add(x, y):
        return x + y
     
    # 在另一个文件中
    from mymodule import add
    print(add(2, 3))

1.4 输入输出

  • input()name = input("Enter your name: ") print(f"Hello, {name}!")

  • print()print("This is a print statement.")

2. 面向对象编程

2.1 类与对象

  • 类:

    复制代码
    class Dog:
        def __init__(self, name, age):
            self.name = name
            self.age = age
     
        def bark(self):
            return "Woof!"
  • 对象:my_dog = Dog("Buddy", 3) print(my_dog.name) print(my_dog.bark())

2.2 继承与多态

  • 继承:

    复制代码
    class Animal:
        def speak(self):
            pass
     
    class Dog(Animal):
        def speak(self):
            return "Woof!"
  • 多态:def animal_speak(animal): print(animal.speak()) animal_speak(Dog())

2.3 封装与抽象

  • 封装:

    复制代码
    class BankAccount:
        def __init__(self, balance=0):
            self.__balance = balance  # 私有属性
     
        def deposit(self, amount):
            self.__balance += amount
     
        def get_balance(self):
            return self.__balance
  • 抽象:

    复制代码
    from abc import ABC, abstractmethod
     
    class Shape(ABC):
        @abstractmethod
        def area(self):
            pass
     
    class Circle(Shape):
        def __init__(self, radius):
            self.radius = radius
     
        def area(self):
            return 3.14 * self.radius ** 2

3. 文件操作

3.1 打开与关闭文件:

python 复制代码
with open('example.txt', 'w') as file:
    file.write("Hello, World!")

3.2 读取与写入文件:

python 复制代码
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

4. 异常处理

4.1tryexceptelsefinally语句:

python 复制代码
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print("Division successful!")
finally:
    print("This block is always executed.")

4.2 自定义异常:

python 复制代码
#自定义异常

class CustomError(Exception):
    pass
 
try:
    raise CustomError("This is a custom error message.")
except CustomError as e:
    print(e)

5. 高级特性

5.1 生成器与迭代器:

python 复制代码
def my_generator():
    yield 1
    yield 2
    yield 3
 
gen = my_generator()
for value in gen:
    print(value)

5.2 装饰器:

python 复制代码
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper
 
@my_decorator
def say_hello():
    print("Hello!")
 
say_hello()

5.3 上下文管理器:

python 复制代码
class MyContextManager:
    def __enter__(self):
        print("Entering the context.")
        return self
 
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Exiting the context.")
 
with MyContextManager() as cm:
    print("Inside the context.")

5.4 闭包:

python 复制代码
def make_multiplier(factor):
    def multiplier(number):
        return number * factor
    return multiplier
 
times_two = make_multiplier(2)
print(times_two(5))  # 输出: 10

5.5 列表推导式(List Comprehensions):

python 复制代码
squares = [x**2 for x in range(10)]
print(squares)  # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

5.6 字典推导式(Dictionary Comprehensions):

python 复制代码
square_dict = {x: x**2 for x in range(5)}
print(square_dict)  # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

5.7 集合推导式(Set Comprehensions):

python 复制代码
unique_squares = {x**2 for x in [1, -1, 2, -2, 3]}
print(unique_squares)  # 输出: {1, 4, 9}

5.8 枚举(Enumerations):

python 复制代码
from enum import Enum
 
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
 
print(Color.RED)  # 输出: Color.RED
print(Color.RED.value)  # 输出: 1

5.9 类型注解(Type Annotations):

python 复制代码
def greet(name: str) -> str:
    return f"Hello, {name}!"
 
print(greet("Alice"))  # 输出: Hello, Alice!

6. 标准库与第三方库

在Python中,标准库提供了许多内置模块,用于执行各种常见任务。此外,还有大量的第三方库可供使用,这些库扩展了Python的功能,使其能够处理更复杂的问题。

6.1 标准库

string 库:提供了一系列关于字符串的常量,比如字母、数字、标点符号等。

python 复制代码
import string
print(string.ascii_letters)  # 打印所有ASCII字母(小写和大写)
print(string.digits)         # 打印所有数字
print(string.punctuation)    # 打印所有标点符号

json 库:用于处理JSON数据,包括编码(序列化)和解码(反序列化)Python对象。

python 复制代码
import json
data = {"name": "Alice", "age": 25, "city": "New York"}
json_data = json.dumps(data)  # 将Python对象编码为JSON字符串
print(json_data)
parsed_data = json.loads(json_data)  # 将JSON字符串解码为Python对象
print(parsed_data)

random 库:用于生成随机数。

python 复制代码
import random
print(random.randint(1, 10))  # 生成1到10之间的随机整数
print(random.random())        # 生成0到1之间的随机浮点数
print(random.choice(['apple', 'banana', 'cherry']))  # 从列表中随机选择一个元素

re 库:提供了正则表达式的支持,用于字符串匹配和替换。

python 复制代码
import re
text = "Hello, world! This is a test."
matches = re.findall(r'\b\w+\b', text)  # 匹配并打印所有单词
print(matches)
replaced_text = re.sub(r'\s+', '_', text)  # 替换所有空格为下划线
print(replaced_text)

os 库:用于与操作系统交互,比如文件路径操作、环境变量访问等。

python 复制代码
import os
print(os.getcwd())  # 打印当前工作目录
os.makedirs('new_directory', exist_ok=True)  # 创建目录
print(os.listdir('.'))  # 列出目录内容
os.chdir('new_directory')  # 改变当前工作目录
file_size = os.path.getsize('some_file.txt') if os.path.exists('some_file.txt') else 0
print(file_size)  # 获取文件大小
os.remove('some_file.txt') if os.path.exists('some_file.txt') else None  # 删除文件
os.rmdir('new_directory') if os.path.exists('new_directory') and not os.listdir('new_directory') else None  # 删除空目录

hashlib 库:用于生成安全哈希和消息摘要。

python 复制代码
import hashlib
md5_hash = hashlib.md5()
md5_hash.update(b'Hello, world!')
print(md5_hash.hexdigest())  # 打印MD5哈希值
sha256_hash = hashlib.sha256()
sha256_hash.update(b'Hello, world!')
print(sha256_hash.hexdigest())  # 打印SHA-256哈希值

base64 库:用于对数据进行Base64编码和解码。

python 复制代码
import base64
encoded_data = base64.b64encode(b'Hello, world!')
print(encoded_data)
decoded_data = base64.b64decode(encoded_data)
print(decoded_data.decode('utf-8'))  # 打印解码后的字符串

sys 库:用于访问与Python解释器紧密相关的变量和函数,比如Python版本、命令行参数等。

python 复制代码
import sys
print(sys.version)  # 打印Python版本

math 库:提供了一系列数学函数,比如平方根、三角函数等。

python 复制代码
import math
print(math.sqrt(16))  # 打印16的平方根

datetime 库:用于处理日期和时间。

python 复制代码
from datetime import datetime
print(datetime.now())  # 打印当前时间

6.2 第三方库

requests:一个简单易用的HTTP库,用于发送HTTP请求。

python 复制代码
import requests
response = requests.get('https://api.github.com')
print(response.json())  # 打印响应的JSON内容

numpy:一个强大的科学计算库,支持多维数组对象、矩阵运算、线性代数、傅里叶变换等。

python 复制代码
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)  # 打印数组

pandas:一个开源的数据分析和操作库,提供了快速、灵活和表达性强的数据结构,旨在使"关系"或"标签"数据的处理工作变得既简单又直观。

python 复制代码
import pandas as pd
df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35]
})
print(df)  # 打印DataFrame

7. 并发编程

并发编程是Python中一个非常重要的领域,它允许程序同时执行多个任务。Python提供了多种实现并发编程的方式,包括多线程、多进程和异步编程等。

7.1 多线程

多线程是一种并发编程技术,它允许在单个程序中同时运行多个线程。每个线程都是一个独立的执行路径,可以并发地执行代码。

使用threading模块

Python的threading模块提供了创建和管理线程的功能。以下是一个简单的多线程示例:

python 复制代码
import threading
import time
 
def worker(thread_id):
    print(f"Thread {thread_id} is starting.")
    time.sleep(2)
    print(f"Thread {thread_id} is ending.")
 
threads = []
for i in range(5):
    thread = threading.Thread(target=worker, args=(i,))
    threads.append(thread)
    thread.start()
 
for thread in threads:
    thread.join()
 
print("All threads have finished.")

在这个示例中,创建5个线程,每个线程都执行worker函数。thread.start()方法用于启动线程,thread.join()方法用于等待线程结束。

7.2 多进程

多进程是另一种并发编程技术,它通过在多个进程中运行代码来实现并发。与多线程相比,多进程通常具有更好的性能和资源利用率,因为每个进程都有自己的内存空间和系统资源。

使用multiprocessing模块

Python的multiprocessing模块提供了创建和管理进程的功能。以下是一个简单的多进程示例:

python 复制代码
import multiprocessing
import time
 
def worker(process_id):
    print(f"Process {process_id} is starting.")
    time.sleep(2)
    print(f"Process {process_id} is ending.")
 
processes = []
for i in range(5):
    process = multiprocessing.Process(target=worker, args=(i,))
    processes.append(process)
    process.start()
 
for process in processes:
    process.join()
 
print("All processes have finished.")

在这个示例中,创建5个进程,每个进程都执行worker函数。process.start()方法用于启动进程,process.join()方法用于等待进程结束。

7.3 异步编程

异步编程是一种并发编程技术,它允许程序在等待I/O操作(如网络请求、文件读写等)完成时继续执行其他任务。Python的asyncio库提供了异步编程的支持。

使用asyncio

以下是一个简单的异步编程示例:

python 复制代码
import asyncio
 
async def fetch(url):
    print(f"Starting fetch of {url}")
    await asyncio.sleep(2)  # 模拟网络请求
    print(f"Finished fetch of {url}")
 
async def main():
    tasks = [fetch('http://example.com') for _ in range(5)]
    await asyncio.gather(*tasks)
 
asyncio.run(main())

在这个示例中,定义一个异步函数fetch,它模拟了一个网络请求。main函数创建了5个异步任务,并使用asyncio.gather方法同时运行它们。asyncio.run(main())用于运行异步程序。

7.4 线程池和进程池

为了更高效地管理线程和进程,Python提供了线程池和进程池的概念。线程池和进程池允许你限制并发任务的数量,并重用现有的线程或进程,从而减少了创建和销毁线程或进程的开销。

使用concurrent.futures模块

concurrent.futures模块提供了ThreadPoolExecutorProcessPoolExecutor类,用于创建线程池和进程池。以下是一个简单的示例:

python 复制代码
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
 
def worker(thread_id):
    print(f"Thread {thread_id} is starting.")
    time.sleep(2)
    print(f"Thread {thread_id} is ending.")
    return thread_id
 
with ThreadPoolExecutor(max_workers=3) as executor:
    futures = [executor.submit(worker, i) for i in range(5)]
    for future in as_completed(futures):
        result = future.result()
        print(f"Result: {result}")

在这个示例中,创建一个最大容量为3的线程池,并提交了5个任务。as_completed函数用于迭代已完成的任务,并获取其结果。

以上是对Python的一些基本介绍和示例。在实际应用中,需要根据具体的需求和场景选择合适的并发编程技术。

许久未更新您猜怎么着,整理编写实属不易 有点费人,麻烦各位动动发财的小手,点赞收藏评论支持一波 谢谢!

相关推荐
bluebonnet2720 分钟前
【agent开发】部署LLM(一)
python·llama
HHBon1 小时前
判断用户输入昵称是否存在(Python)
linux·开发语言·python
敢敢变成了憨憨2 小时前
java操作服务器文件(把解析过的文件迁移到历史文件夹地下)
java·服务器·python
苇柠2 小时前
Java补充(Java8新特性)(和IO都很重要)
java·开发语言·windows
敲键盘的小夜猫2 小时前
Milvus向量Search查询综合案例实战(下)
数据库·python·milvus
156082072193 小时前
在QT中,利用charts库绘制FFT图形
开发语言·qt
简简单单做算法3 小时前
基于mediapipe深度学习的虚拟画板系统python源码
人工智能·python·深度学习·mediapipe·虚拟画板
小鹭同学_3 小时前
Java基础 Day27
java·开发语言
EdmundXjs4 小时前
IO Vs NIO
java·开发语言·nio
why1514 小时前
字节golang后端二面
开发语言·后端·golang