Programming·

Python速查表

涵盖了大部分常用的 Python 语法和功能.

基本语法

# 打印
print("Hello, World!")

# 变量赋值
x = 5
y = "Python"

# 注释
# 这是单行注释
"""
这是多行注释
"""

# 数据类型
integer = 10
float_number = 10.5
string = "Hello"
boolean = True
none_value = None

数据结构

# 列表
my_list = [1, 2, 3, "four", 5.0]

# 元组
my_tuple = (1, 2, 3, "four", 5.0)

# 字典
my_dict = {"name": "Alice", "age": 25}

# 集合
my_set = {1, 2, 3, 4, 5}

控制结构

# 条件语句
if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")

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

# while 循环
count = 0
while count < 5:
    print(count)
    count += 1

函数

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

# 调用函数
print(greet("Alice"))

类和对象

# 定义类
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

# 创建对象
person = Person("Alice", 25)
print(person.greet())

文件操作

# 读取文件
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

# 写入文件
with open("example.txt", "w") as file:
    file.write("Hello, World!")

异常处理

try:
    # 可能会引发异常的代码
    result = 10 / 0
except ZeroDivisionError:
    print("除零错误")
finally:
    print("无论如何都会执行")

常用库

# NumPy
import numpy as np
array = np.array([1, 2, 3])

# Pandas
import pandas as pd
df = pd.DataFrame({"Name": ["Alice", "Bob"], "Age": [25, 30]})

# Matplotlib
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()

# Requests
import requests
response = requests.get("https://api.github.com")
print(response.json())

高级主题

# 列表推导式
squares = [x**2 for x in range(10)]

# Lambda 函数
add = lambda a, b: a + b
print(add(5, 3))

# 装饰器
def decorator_function(original_function):
    def wrapper_function():
        print("Wrapper executed before {}".format(original_function.__name__))
        return original_function()
    return wrapper_function

@decorator_function
def display():
    print("Display function ran")

display()