Python 学习笔记
一、Python 简介
二、Python 基础语法
2.1 变量与数据类型
x = 5 # 整数类型y = 3.14 # 浮点数类型name = "John" # 字符串类型is_student = True # 布尔类型
fruits = ["apple", "banana", "cherry"]fruits.append("orange") # 在列表末尾添加元素fruits[1] = "pear" # 修改列表中的元素
point = (3, 4)
set1 = {1, 2, 3}set2 = {3, 4, 5}union_set = set1.union(set2) # 求并集
person = {"name": "Alice", "age": 25, "city": "New York"}print(person["name"]) # 输出 "Alice"
2.2 运算符
a = 10b = 3print(a + b) # 输出 13print(a > b) # 输出 Trueprint("a" in "abc") # 输出 True
2.3 控制流语句
age = 18if age < 18:print("未成年")elif age == 18:print("刚刚成年")else:print("已成年")
fruits = ["apple", "banana", "cherry"]for fruit in fruits:print(fruit)
i = 0while i < 5:print(i)i += 1
三、函数与模块
3.1 函数定义与调用
def add(a, b):return a + bresult = add(3, 5)print(result) # 输出 8
def greet(name="Guest"):print(f"Hello, {name}!")greet() # 输出 "Hello, Guest!"greet("Alice") # 输出 "Hello, Alice!"
3.2 模块与包
import mathprint(math.sqrt(16)) # 输出 4.0
from math import piprint(pi) # 输出 3.141592653589793
四、面向对象编程
4.1 类与对象
class Dog:def __init__(self, name, age):self.name = nameself.age = agedef bark(self):print(f"{self.name} says Woof!")my_dog = Dog("Buddy", 3)my_dog.bark() # 输出 "Buddy says Woof!"
4.2 继承与多态
class Animal:def speak(self):print("The animal makes a sound")class Cat(Animal):def speak(self):print("Meow")animal = Animal()cat = Cat()animal.speak() # 输出 "The animal makes a sound"cat.speak() # 输出 "Meow"
五、文件操作
'r':只读模式(默认)
'w':写入模式(覆盖原有内容)
'a':追加模式
'rb':二进制只读模式
'wb':二进制写入模式
with open('test.txt', 'r') as file:content = file.read()print(content)
with open('test.txt', 'w') as file:file.write("Hello, World!")
六、异常处理
try:result = 10 / 0except ZeroDivisionError:print("不能除以零")
file = Nonetry:file = open('test.txt', 'r')content = file.read()except FileNotFoundError:print("文件不存在")finally:if file:file.close()
七、Python 高级特性
7.1 列表推导式
numbers = [1, 2, 3, 4, 5]squared_numbers = [x ** 2 for x in numbers]print(squared_numbers) # 输出 [1, 4, 9, 16, 25]
even_numbers = [x for x in numbers if x % 2 == 0]print(even_numbers) # 输出 [2, 4]
7.2 生成器
numbers = (x ** 2 for x in range(10))for num in numbers:print(num)
def fibonacci():a, b = 0, 1while True:yield aa, b = b, a + bfib = fibonacci()for _ in range(10):print(next(fib))
7.3 装饰器
import timedef timer(func):def wrapper():start = time.time()func()end = time.time()print(f"函数执行时间: {end - start} 秒")return wrapper@timerdef say_hello():time.sleep(2)print("Hello!")say_hello()