Skip to content

Python

一种解释型、高级编程语言

官方网站

简介

Python 是一种解释型、面向对象、动态数据类型的高级程序设计语言。由 Guido van Rossum 于 1989 年发明,第一个公开版本于 1991 年发布。Python 的设计哲学强调代码的可读性和简洁的语法。

语言特性

  • 简洁易读:语法简洁,接近自然语言
  • 跨平台:支持 Windows、macOS、Linux 等主流操作系统
  • 解释型:无需编译,直接运行
  • 面向对象:支持类、继承、多态等 OOP 特性
  • 动态类型:运行时进行类型检查
  • 丰富的标准库:内置大量实用模块
  • 第三方生态:拥有庞大的第三方包生态系统

安装

Windows

bash
# 下载安装程序:https://www.python.org/downloads/
# 或使用 winget
winget install Python.Python.3.12

# 安装后添加到 PATH

macOS

bash
# 使用 Homebrew
brew install python@3.12

# 使用 pyenv 管理多版本
brew install pyenv
pyenv install 3.12.0
pyenv global 3.12.0

Linux (Ubuntu/Debian)

bash
sudo apt update
sudo apt install python3 python3-pip python3-venv

# 或使用 pyenv
curl https://pyenv.run | bash

验证安装

bash
python3 --version
pip3 --version

基本语法

1. 变量与数据类型

python
# 变量
name = "Alice"  # 字符串
age = 25        # 整数
height = 1.68   # 浮点数
is_student = True  # 布尔值

# 多变量赋值
x, y, z = 1, 2, 3

# 常量(约定俗成)
PI = 3.14159
MAX_SIZE = 100

2. 字符串

python
# 字符串创建
single_quotes = 'Hello'
double_quotes = "World"
multiline = """
This is a
multiline string
"""

# 字符串格式化
name = "Alice"
age = 25

# f-string(Python 3.6+)
print(f"My name is {name}, I'm {age} years old")

# format 方法
print("My name is {}, I'm {} years old".format(name, age))

# 字符串方法
s = "Hello, World!"
print(s.upper())      # HELLO, WORLD!
print(s.lower())      # hello, world!
print(s.split(","))   # ['Hello', ' World!']
print(s.strip())      # Hello, World!
print(s.replace("World", "Python"))  # Hello, Python!
print(s[0])           # H
print(s[0:5])         # Hello

3. 运算符

python
# 算术运算符
a = 10
b = 3
print(a + b)   # 13 加法
print(a - b)   # 7  减法
print(a * b)   # 30 乘法
print(a / b)   # 3.333... 除法
print(a // b)  # 3  整除
print(a % b)   # 1  取余
print(a ** b)  # 1000 幂运算

# 比较运算符
print(a == b)  # False 等于
print(a != b)  # True  不等于
print(a > b)   # True  大于
print(a < b)   # False 小于
print(a >= b)  # True  大于等于
print(a <= b)  # False 小于等于

# 逻辑运算符
x = True
y = False
print(x and y)  # False 逻辑与
print(x or y)   # True  逻辑或
print(not x)    # False 逻辑非

# 位运算符
print(a & b)    # 2  按位与
print(a | b)    # 11 按位或
print(a ^ b)    # 9  按位异或
print(~a)       # -11 按位取反
print(a << 2)   # 40 左移
print(a >> 2)   # 2  右移

4. 列表

python
# 创建列表
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]

# 访问元素
print(fruits[0])       # apple
print(fruits[-1])      # cherry(最后一个)

# 切片
print(fruits[0:2])     # ['apple', 'banana']
print(fruits[::2])     # ['apple', 'cherry']

# 修改元素
fruits[0] = "apricot"

# 添加元素
fruits.append("date")           # 末尾添加
fruits.insert(1, "blueberry")   # 指定位置插入
fruits.extend(["elderberry"])   # 扩展列表

# 删除元素
fruits.remove("banana")  # 移除第一个匹配项
popped = fruits.pop()    # 弹出并返回最后一个
del fruits[0]            # 删除指定位置元素
fruits.clear()           # 清空列表

# 列表方法
print(len(fruits))           # 长度
print(fruits.index("apple")) # 查找元素索引
print(fruits.count("apple")) # 统计元素出现次数
fruits.sort()                # 排序
fruits.reverse()             # 反转

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

5. 元组

python
# 创建元组
coordinates = (10, 20, 30)
single_element = (42,)  # 注意逗号

# 访问元素
print(coordinates[0])   # 10
print(coordinates[1:])  # (20, 30)

# 元组不可变
# coordinates[0] = 100  # 会报错

# 元组解包
x, y, z = coordinates
print(f"x={x}, y={y}, z={z}")

# 命名元组
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y)

6. 字典

python
# 创建字典
person = {
    "name": "Alice",
    "age": 25,
    "city": "Beijing"
}

# 访问元素
print(person["name"])       # Alice
print(person.get("email", "N/A"))  # 使用 get 安全获取

# 添加/修改元素
person["email"] = "alice@example.com"
person["age"] = 26

# 删除元素
del person["city"]
email = person.pop("email")

# 字典方法
print(person.keys())        # 所有键
print(person.values())      # 所有值
print(person.items())       # 所有键值对
person.update({"phone": "1234567890"})

# 字典推导式
squares = {x: x**2 for x in range(5)}

7. 集合

python
# 创建集合
fruits = {"apple", "banana", "cherry"}
numbers = set([1, 2, 3, 4, 5])

# 添加元素
fruits.add("date")

# 删除元素
fruits.remove("banana")    # 不存在会报错
fruits.discard("banana")   # 不存在不报错

# 集合运算
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1 | set2)  # 并集 {1, 2, 3, 4}
print(set1 & set2)  # 交集 {2, 3}
print(set1 - set2)  # 差集 {1}
print(set1 ^ set2)  # 对称差集 {1, 4}

流程控制

1. 条件语句

python
age = 18

if age < 18:
    print("未成年")
elif age < 65:
    print("成年人")
else:
    print("老年人")

# 三元表达式
status = "成年" if age >= 18 else "未成年"

2. 循环语句

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

for fruit in ["apple", "banana", "cherry"]:
    print(fruit)

for key, value in person.items():
    print(f"{key}: {value}")

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

# break, continue, else
for i in range(10):
    if i == 5:
        break
    if i % 2 == 0:
        continue
    print(i)
else:
    print("循环正常结束")  # 不使用 break 时执行

3. 推导式

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

# 字典推导式
square_dict = {x: x**2 for x in range(5)}

# 集合推导式
unique_squares = {x**2 for x in range(-3, 4)}

# 生成器表达式
gen = (x**2 for x in range(10))

函数

python
# 定义函数
def greet(name):
    """简单的问候函数"""
    return f"Hello, {name}!"

# 默认参数
def power(base, exponent=2):
    return base ** exponent

# 关键字参数
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

# 可变参数
def sum_all(*args):
    return sum(args)

def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# 类型提示
def add(a: int, b: int) -> int:
    return a + b

# Lambda 函数
square = lambda x: x ** 2
add = lambda x, y: x + y

# 高阶函数
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2, numbers)
evens = filter(lambda x: x % 2 == 0, numbers)
from functools import reduce
total = reduce(lambda x, y: x + y, numbers)

类与对象

python
class Person:
    # 类属性
    species = "Human"

    # 初始化方法
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # 实例方法
    def greet(self):
        return f"Hello, I'm {self.name}"

    # 类方法
    @classmethod
    def create_anonymous(cls):
        return cls("Anonymous", 0)

    # 静态方法
    @staticmethod
    def is_adult(age):
        return age >= 18

    # 属性
    @property
    def adult(self):
        return self.age >= 18


# 继承
class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id

    def study(self):
        return f"{self.name} is studying"


# 多态
class Teacher(Person):
    def teach(self):
        return f"{self.name} is teaching"


def introduce(person: Person):
    if isinstance(person, Person):
        print(person.greet())

异常处理

python
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except (ValueError, TypeError) as e:
    print(f"Error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
else:
    print("No errors occurred!")
finally:
    print("This always executes")

# 自定义异常
class CustomError(Exception):
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

# 抛出异常
def validate_age(age):
    if age < 0:
        raise CustomError("Age cannot be negative")
    return age

# 使用 raise
try:
    validate_age(-5)
except CustomError as e:
    print(e.message)

文件操作

python
# 读取文件
with open("example.txt", "r", encoding="utf-8") as f:
    content = f.read()           # 读取全部
    lines = f.readlines()        # 读取所有行

# 逐行读取
with open("example.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

# 写入文件
with open("example.txt", "w", encoding="utf-8") as f:
    f.write("Hello, World!\n")

# 追加文件
with open("example.txt", "a", encoding="utf-8") as f:
    f.write("Another line\n")

# JSON 文件
import json

data = {"name": "Alice", "age": 25, "hobbies": ["reading", "coding"]}

with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

with open("data.json", "r", encoding="utf-8") as f:
    loaded_data = json.load(f)

# CSV 文件
import csv

with open("data.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "age", "city"])
    writer.writerow(["Alice", 25, "Beijing"])
    writer.writerow(["Bob", 30, "Shanghai"])

with open("data.csv", "r", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"], row["age"])

模块与包

python
# 导入模块
import math
print(math.sqrt(16))

from math import sqrt, pi
print(sqrt(16))
print(pi)

import math as m
print(m.floor(3.7))

# 创建模块(my_module.py)
# def greet(name):
#     return f"Hello, {name}!"

# 导入自定义模块
import my_module
print(my_module.greet("Alice"))

# __init__.py 使目录成为包
# from package import module

# 相对导入
from . import another_module
from .module import some_function

虚拟环境

bash
# 使用 venv 创建虚拟环境
python3 -m venv myenv

# 激活虚拟环境
# Windows
myenv\Scripts\activate
# Linux/macOS
source myenv/bin/activate

# 停用虚拟环境
deactivate

# 使用 pip 管理包
pip install requests
pip install numpy pandas matplotlib
pip install --upgrade pip
pip list
pip freeze > requirements.txt
pip install -r requirements.txt

常用标准库

python
# os - 操作系统接口
import os
os.getcwd()           # 当前工作目录
os.listdir(".")       # 列出目录内容
os.makedirs("new_dir", exist_ok=True)  # 创建目录
os.remove("file.txt") # 删除文件

# sys - 系统功能
import sys
sys.argv              # 命令行参数
sys.version           # Python 版本
sys.exit(0)           # 退出程序

# datetime - 日期时间
from datetime import datetime, date, timedelta
now = datetime.now()
today = date.today()
tomorrow = today + timedelta(days=1)

# collections - 容器数据类型
from collections import defaultdict, Counter, deque
d = defaultdict(list)
c = Counter("hello")
dq = deque([1, 2, 3])

# itertools - 迭代工具
import itertools
list(itertools.chain([1, 2], [3, 4]))  # [1, 2, 3, 4]
list(itertools.combinations([1, 2, 3], 2))  # [(1, 2), (1, 3), (2, 3)]

# functools - 高阶函数
from functools import lru_cache, reduce
@lru_cache(maxsize=128)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

# re - 正则表达式
import re
pattern = r"\d+"
matches = re.findall(pattern, "abc123def456")

# logging - 日志
import logging
logging.basicConfig(level=logging.INFO)
logging.info("This is an info message")

最佳实践

  1. 遵循 PEP 8:使用 Black 或 Ruff 自动格式化代码
  2. 类型注解:为函数和变量添加类型提示
  3. 使用虚拟环境:每个项目使用独立的虚拟环境
  4. 编写文档:为函数和模块编写 docstring
  5. 异常处理:不要吞掉异常,使用具体的异常类型
  6. 使用列表推导式:简洁的列表操作
  7. 上下文管理器:使用 with 语句管理资源
  8. 单元测试:使用 unittestpytest 编写测试