Python 支持多种数据类型,包括整数、浮点数、字符串、布尔值、列表、元组、字典等。
# 整数
x = 10
# 浮点数
y = 3.14
# 字符串
name = "Python"
# 布尔值
is_valid = True
# 列表
numbers = [1, 2, 3, 4, 5]
# 字典
person = {"name": "Alice", "age": 30}
Python 支持 if-elif-else 条件语句和 for、while 循环语句。
# if-elif-else 语句
if x > 0:
print("正数")
elif x < 0:
print("负数")
else:
print("零")
# for 循环
for i in range(5):
print(i)
# while 循环
while x > 0:
print(x)
x -= 1
Python 是一种面向对象的编程语言,支持类和对象的概念。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name}")
# 创建对象
p = Person("Bob", 25)
p.greet() # 输出: Hello, my name is Bob
Python 支持类的继承和多态特性。
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def study(self):
print(f"{self.name} is studying")
# 创建学生对象
s = Student("Alice", 20, "S12345")
s.greet() # 继承自Person类的方法
s.study() # 学生类的特有方法
NumPy 是 Python 中用于科学计算的核心库,提供了高性能的多维数组对象和各种数学函数。
import numpy as np # 创建数组 arr = np.array([1, 2, 3, 4, 5]) # 数组运算 arr_squared = arr ** 2 # 矩阵操作 matrix = np.array([[1, 2], [3, 4]]) determinant = np.linalg.det(matrix)
Pandas 是 Python 中用于数据分析的库,提供了 DataFrame 结构,方便进行数据处理和分析。
import pandas as pd
# 创建 DataFrame
data = {
"name": ["Alice", "Bob", "Charlie"],
"age": [25, 30, 35],
"city": ["New York", "London", "Paris"]
}
df = pd.DataFrame(data)
# 数据操作
print(df.head()) # 查看前几行
print(df.describe()) # 统计描述
# 数据筛选
young_people = df[df["age"] < 30]
Matplotlib 是 Python 中用于数据可视化的库,可以创建各种类型的图表。
import matplotlib.pyplot as plt
# 创建数据
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
# 绘制图表
plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.show()
列表推导式是 Python 中一种简洁创建列表的方法。
# 传统方法
squares = []
for i in range(10):
squares.append(i ** 2)
# 列表推导式
squares = [i ** 2 for i in range(10)]
# 带条件的列表推导式
even_squares = [i ** 2 for i in range(10) if i % 2 == 0]
生成器是一种特殊的迭代器,可以按需生成值,节省内存。
# 生成器函数
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# 使用生成器
for num in fibonacci(10):
print(num)
# 生成器表达式
squares = (i ** 2 for i in range(10))
装饰器是一种修改函数行为的方法,可以在不修改原函数代码的情况下增强函数功能。
def timer(func):
def wrapper(*args, **kwargs):
import time
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} took {end_time - start_time:.4f} seconds")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return "Done"
slow_function() # 输出执行时间