Python基础语法完全指南:从零入门到掌握核心概念

前言:为什么Python如此受欢迎?

Python作为当今最流行的编程语言之一,以其简洁优雅的语法强大的生态体系广泛的应用场景征服了无数开发者。无论你是编程新手还是有经验的开发者,Python都能为你打开一扇通往人工智能、数据分析、Web开发等领域的大门。

第一章:Python起步与环境搭建

1.1 Python安装与配置

bash 复制代码
# 检查Python版本
python --version
python -V

# Python 3.x 和 Python 2.x 区分
python3 --version  # Linux/Mac上通常使用python3

# 启动Python交互式环境
python  # 或 python3

# 退出交互式环境
exit()  # 或 Ctrl+D (Linux/Mac) / Ctrl+Z (Windows)

1.2 编写第一个Python程序

python 复制代码
# hello.py
print("Hello, Python World!")  # 打印输出

# 运行程序
# python hello.py

1.3 代码注释规范

python 复制代码
# 单行注释 - 以#开头,解释代码功能
print("Hello")  # 这里也是注释

"""
多行注释(文档字符串)
三个双引号或单引号
用于函数、类的文档说明
"""

'''
这也是多行注释
可以跨越多行
'''

def calculate_sum(a, b):
    """
    计算两个数的和
    
    参数:
        a (int/float): 第一个数字
        b (int/float): 第二个数字
        
    返回:
        int/float: 两个数的和
    """
    return a + b

第二章:Python基础数据类型

2.1 数值类型(Numbers)

python 复制代码
# 整数(int)
age = 25
count = -10
big_number = 1_000_000  # 使用下划线提高可读性

# 浮点数(float)
price = 19.99
pi = 3.1415926
scientific = 1.23e-4  # 科学计数法

# 复数(complex)
z = 3 + 4j
print(z.real)  # 实部:3.0
print(z.imag)  # 虚部:4.0

# 类型转换
int_num = int(3.14)    # 3
float_num = float(3)   # 3.0
complex_num = complex(3, 4)  # (3+4j)

# 数值运算
a, b = 10, 3
print(a + b)   # 加法: 13
print(a - b)   # 减法: 7
print(a * b)   # 乘法: 30
print(a / b)   # 除法: 3.3333333333333335
print(a // b)  # 整除: 3
print(a % b)   # 取余: 1
print(a ** b)  # 幂运算: 1000

2.2 布尔类型(Boolean)

python 复制代码
# 布尔值
is_active = True
is_deleted = False

# 布尔运算
print(True and False)  # False
print(True or False)   # True
print(not True)        # False

# 布尔转换
print(bool(1))     # True
print(bool(0))     # False
print(bool(""))    # False (空字符串)
print(bool("Hi"))  # True (非空字符串)
print(bool([]))    # False (空列表)
print(bool([1]))   # True (非空列表)

# 比较运算符
print(5 > 3)    # True
print(5 == 5)   # True
print(5 != 3)   # True
print(5 >= 5)   # True
print(5 <= 6)   # True

2.3 字符串(String)

python 复制代码
# 字符串创建
name = "Alice"
name2 = 'Bob'
multi_line = """多行
字符串"""
multi_line2 = '''另一个
多行字符串'''

# 字符串索引和切片
text = "Hello, Python!"
print(text[0])     # H (第一个字符)
print(text[-1])    # ! (最后一个字符)
print(text[0:5])   # Hello (切片:开始到结束-1)
print(text[7:])    # Python! (从索引7到结尾)
print(text[:5])    # Hello (从头到索引5-1)
print(text[::2])   # Hlo yhn (步长为2)

# 字符串常用方法
text = "  Hello, World!  "
print(text.strip())        # "Hello, World!" (去除两边空格)
print(text.lower())        # "  hello, world!  "
print(text.upper())        # "  HELLO, WORLD!  "
print(text.replace("World", "Python"))  # "  Hello, Python!  "
print(text.split(","))     # ['  Hello', ' World!  ']
print(",".join(["a", "b", "c"]))  # "a,b,c"
print(text.find("World"))  # 9 (找到的位置)
print(text.count("l"))     # 3 (统计出现次数)

# 字符串格式化(三种方式)
name = "Alice"
age = 25

# 1. f-string (Python 3.6+ 推荐)
print(f"My name is {name} and I'm {age} years old.")
print(f"Next year I'll be {age + 1}")

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

# 3. %格式化 (传统方式)
print("My name is %s and I'm %d years old." % (name, age))

# 字符串转义
print("She said: \"Hello!\"")  # She said: "Hello!"
print('It\'s a beautiful day') # It's a beautiful day
print("First line\nSecond line")  # \n 换行
print("Tab\there")  # \t 制表符
print("Backslash: \\")  # \\

第三章:Python复合数据类型

3.1 列表(List) - 有序的可变序列

python 复制代码
# 列表创建
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "apple", True, 3.14]
empty_list = []
list_from_range = list(range(5))  # [0, 1, 2, 3, 4]

# 列表操作
fruits = ["apple", "banana", "cherry"]

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

# 修改元素
fruits[1] = "blueberry"

# 添加元素
fruits.append("orange")        # 末尾添加
fruits.insert(1, "grape")      # 指定位置插入

# 删除元素
removed = fruits.pop()         # 删除并返回最后一个元素
removed2 = fruits.pop(1)       # 删除指定位置元素
fruits.remove("apple")         # 删除指定值的第一个匹配项
del fruits[0]                  # 删除指定位置元素

# 列表合并
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2       # [1, 2, 3, 4, 5, 6]
list1.extend(list2)            # list1变为[1, 2, 3, 4, 5, 6]

# 列表切片
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5])    # [2, 3, 4]
print(numbers[:3])     # [0, 1, 2]
print(numbers[5:])     # [5, 6, 7, 8, 9]
print(numbers[::2])    # [0, 2, 4, 6, 8] (步长为2)
print(numbers[::-1])   # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] (反转)

# 列表推导式(强大特性)
squares = [x**2 for x in range(10)]  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
even_squares = [x**2 for x in range(10) if x % 2 == 0]  # 偶数平方
nested = [(x, y) for x in range(3) for y in range(3)]  # 嵌套循环

# 列表常用方法
numbers = [3, 1, 4, 1, 5, 9]
print(len(numbers))        # 长度: 6
numbers.sort()             # 排序: [1, 1, 3, 4, 5, 9]
numbers.reverse()          # 反转: [9, 5, 4, 3, 1, 1]
print(numbers.count(1))    # 计数: 2
print(numbers.index(4))    # 索引: 2
numbers.clear()            # 清空列表

3.2 元组(Tuple) - 有序的不可变序列

python 复制代码
# 元组创建
coordinates = (10, 20)
person = ("Alice", 25, "Engineer")
single_element = (42,)     # 注意逗号!(42)只是整数42
empty_tuple = ()

# 元组解包
x, y = coordinates  # x=10, y=20
name, age, job = person

# 交换变量值(Pythonic方式)
a, b = 1, 2
a, b = b, a  # a=2, b=1

# 元组操作(类似列表,但不能修改)
print(coordinates[0])      # 10
print(coordinates[0:2])    # (10, 20)
print(len(coordinates))    # 2
print(10 in coordinates)   # True

# 返回多个值的函数
def get_user_info():
    return "Alice", 25, "alice@example.com"

name, age, email = get_user_info()

3.3 字典(Dictionary) - 键值对映射

python 复制代码
# 字典创建
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

# 使用dict()构造函数
person2 = dict(name="Bob", age=30, city="London")
person3 = dict([("name", "Charlie"), ("age", 35)])

# 访问字典
print(person["name"])           # Alice
print(person.get("age"))        # 25
print(person.get("country", "USA"))  # 如果键不存在,返回默认值"USA"

# 修改字典
person["age"] = 26              # 修改值
person["country"] = "USA"       # 添加新键值对
person.update({"job": "Engineer", "age": 27})  # 批量更新

# 删除元素
del person["city"]              # 删除键值对
age = person.pop("age")         # 删除并返回值
person.clear()                  # 清空字典

# 字典遍历
person = {"name": "Alice", "age": 25, "city": "NYC"}

for key in person:              # 遍历键
    print(key, person[key])

for value in person.values():   # 遍历值
    print(value)

for key, value in person.items():  # 遍历键值对
    print(f"{key}: {value}")

# 字典推导式
squares = {x: x**2 for x in range(5)}  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

3.4 集合(Set) - 无序的唯一元素集合

python 复制代码
# 集合创建
unique_numbers = {1, 2, 3, 4, 5}
empty_set = set()          # 注意:{}创建的是空字典,不是空集合

# 从列表去重
numbers = [1, 2, 2, 3, 3, 3]
unique = set(numbers)      # {1, 2, 3}

# 集合操作
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

print(set1 | set2)    # 并集: {1, 2, 3, 4, 5, 6, 7, 8}
print(set1 & set2)    # 交集: {4, 5}
print(set1 - set2)    # 差集: {1, 2, 3}
print(set1 ^ set2)    # 对称差集: {1, 2, 3, 6, 7, 8}

# 集合方法
numbers = {1, 2, 3}
numbers.add(4)        # 添加元素
numbers.remove(2)     # 移除元素(不存在会报错)
numbers.discard(5)    # 安全移除(不存在不会报错)
numbers.pop()         # 随机移除并返回一个元素
numbers.clear()       # 清空集合

# 集合推导式
unique_chars = {char for char in "hello world"}  # {'h', 'e', 'l', 'o', ' ', 'w', 'r', 'd'}

第四章:Python流程控制

4.1 条件判断(if-elif-else)

python 复制代码
# 基础if语句
age = 18

if age >= 18:
    print("成年人")
else:
    print("未成年人")

# 多条件判断
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"成绩等级: {grade}")

# 嵌套条件
temperature = 25
is_sunny = True

if temperature > 20:
    if is_sunny:
        print("适合户外活动")
    else:
        print("天气温暖但阴天")
else:
    print("天气较冷")

# 三元表达式
age = 20
status = "成年人" if age >= 18 else "未成年人"
print(status)

# 条件链式比较(Python特色)
x = 15
if 10 <= x <= 20:  # 等价于 x >= 10 and x <= 20
    print("x在10到20之间")

# 条件表达式中的逻辑运算符
name = "Alice"
age = 25

if name == "Alice" and age > 20:
    print("符合条件的Alice")

if name == "Bob" or age < 30:
    print("姓名是Bob或年龄小于30")

if not age < 18:
    print("不是未成年人")

4.2 循环结构

4.2.1 for循环
python 复制代码
# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# 遍历字符串
for char in "Python":
    print(char)

# 使用range()函数
for i in range(5):            # 0,1,2,3,4
    print(i)

for i in range(2, 8):         # 2,3,4,5,6,7
    print(i)

for i in range(0, 10, 2):     # 0,2,4,6,8 (步长为2)
    print(i)

# 同时获取索引和值
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"索引{index}: {fruit}")

# 遍历字典
person = {"name": "Alice", "age": 25, "city": "NYC"}
for key, value in person.items():
    print(f"{key}: {value}")

# 嵌套循环
for i in range(3):
    for j in range(3):
        print(f"({i}, {j})")
4.2.2 while循环
python 复制代码
# 基础while循环
count = 0
while count < 5:
    print(count)
    count += 1  # 不要忘记改变条件,否则会无限循环

# 带条件的while循环
password = ""
while password != "secret":
    password = input("请输入密码: ")
print("密码正确!")

# while-else结构
count = 0
while count < 3:
    print(f"尝试 {count+1}")
    count += 1
else:
    print("循环正常结束")

# 无限循环(需要break退出)
while True:
    user_input = input("输入'quit'退出: ")
    if user_input == "quit":
        break
    print(f"你输入了: {user_input}")
4.2.3 循环控制语句
python 复制代码
# break - 跳出整个循环
for i in range(10):
    if i == 5:
        break
    print(i)  # 输出0,1,2,3,4

# continue - 跳过当前迭代
for i in range(5):
    if i == 2:
        continue
    print(i)  # 输出0,1,3,4

# pass - 占位符,什么都不做
for i in range(5):
    if i == 2:
        pass  # 暂时不写实现,保持语法完整
    else:
        print(i)

# else子句(循环正常结束时执行)
for i in range(3):
    print(i)
else:
    print("循环完成")  # 会执行

for i in range(5):
    if i == 2:
        break
    print(i)
else:
    print("循环完成")  # 不会执行,因为break跳出了

第五章:Python函数详解

5.1 函数定义与调用

python 复制代码
# 基础函数
def greet():
    """简单的问候函数"""
    print("Hello, World!")

greet()  # 调用函数

# 带参数的函数
def greet_person(name):
    print(f"Hello, {name}!")

greet_person("Alice")

# 带返回值的函数
def add(a, b):
    """返回两个数的和"""
    return a + b

result = add(3, 5)
print(result)  # 8

# 多个返回值
def get_min_max(numbers):
    """返回列表的最小值和最大值"""
    return min(numbers), max(numbers)

min_val, max_val = get_min_max([1, 5, 3, 9, 2])
print(f"最小值: {min_val}, 最大值: {max_val}")

5.2 参数类型

python 复制代码
# 位置参数
def introduce(name, age, city):
    print(f"我叫{name},今年{age}岁,来自{city}")

introduce("Alice", 25, "New York")  # 必须按顺序传递

# 关键字参数
introduce(age=25, city="London", name="Bob")  # 可以按参数名传递

# 默认参数
def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Alice")            # Hello, Alice!
greet("Bob", "Hi")        # Hi, Bob!

# 注意:默认参数必须放在非默认参数后面
def calculate_price(quantity, price=10.0, discount=0.0):
    return quantity * price * (1 - discount)

# 可变参数 (*args)
def sum_all(*args):
    """接受任意数量的位置参数"""
    total = 0
    for num in args:
        total += num
    return total

print(sum_all(1, 2, 3))          # 6
print(sum_all(1, 2, 3, 4, 5))    # 15

# 关键字可变参数 (**kwargs)
def print_info(**kwargs):
    """接受任意数量的关键字参数"""
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="NYC")

# 混合使用所有参数类型
def complex_func(a, b, *args, option=True, **kwargs):
    print(f"a={a}, b={b}")
    print(f"args={args}")
    print(f"option={option}")
    print(f"kwargs={kwargs}")

complex_func(1, 2, 3, 4, 5, option=False, x=10, y=20)

5.3 函数高级特性

python 复制代码
# 函数作为参数传递
def apply_operation(x, y, operation):
    return operation(x, y)

def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

print(apply_operation(5, 3, add))       # 8
print(apply_operation(5, 3, multiply))  # 15

# lambda表达式(匿名函数)
square = lambda x: x ** 2
print(square(5))  # 25

# 直接在需要函数的地方使用lambda
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))  # [1, 4, 9, 16, 25]

# 闭包
def outer_function(x):
    def inner_function(y):
        return x + y
    return inner_function

add_5 = outer_function(5)  # 创建一个加5的函数
print(add_5(3))  # 8

# 装饰器
def my_decorator(func):
    def wrapper():
        print("函数执行前")
        func()
        print("函数执行后")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
# 输出:
# 函数执行前
# Hello!
# 函数执行后

第六章:Python模块与包

6.1 模块导入

python 复制代码
# 导入整个模块
import math
print(math.sqrt(16))  # 4.0

# 导入特定函数/类
from math import sqrt, pi
print(sqrt(9))  # 3.0
print(pi)       # 3.141592653589793

# 使用别名
import numpy as np
import pandas as pd

# 导入模块所有内容(不推荐,容易命名冲突)
from math import *

# 相对导入(在包内部)
# from . import module_name
# from .. import parent_module

# 检查模块是否可导入
import importlib
module_name = "requests"
if importlib.util.find_spec(module_name):
    import requests
    print(f"{module_name} 已安装")
else:
    print(f"{module_name} 未安装")

6.2 自定义模块

python 复制代码
# mymodule.py
"""
我的自定义模块
提供一些实用函数
"""

VERSION = "1.0.0"

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

def calculate_sum(numbers):
    """计算列表的和"""
    return sum(numbers)

def factorial(n):
    """计算阶乘"""
    if n <= 1:
        return 1
    return n * factorial(n - 1)

# 模块测试代码
if __name__ == "__main__":
    # 这些代码只在直接运行模块时执行
    print("测试mymodule模块:")
    print(greet("Alice"))
    print(calculate_sum([1, 2, 3, 4, 5]))

6.3 包(Package)结构

复制代码
my_package/
├── __init__.py          # 包初始化文件
├── module1.py          # 模块1
├── module2.py          # 模块2
├── subpackage/         # 子包
│   ├── __init__.py
│   └── module3.py
└── utils/              # 另一个子包
    ├── __init__.py
    └── helper.py
python 复制代码
# __init__.py 示例
"""
my_package - 我的Python包
"""

__version__ = "1.0.0"
__author__ = "Your Name"

# 指定导入时导入哪些模块
__all__ = ["module1", "module2"]

# 可以在__init__.py中导入常用函数,方便使用
from .module1 import main_function
from .subpackage.module3 import helper_function

第七章:Python异常处理

7.1 基础异常处理

python 复制代码
# try-except
try:
    result = 10 / 0
except ZeroDivisionError:
    print("不能除以零!")

# 捕获多个异常
try:
    number = int(input("请输入一个数字: "))
    result = 10 / number
except ValueError:
    print("输入的不是有效数字!")
except ZeroDivisionError:
    print("不能除以零!")
except Exception as e:  # 捕获所有其他异常
    print(f"发生未知错误: {e}")

# try-except-else
try:
    file = open("data.txt", "r")
except FileNotFoundError:
    print("文件不存在!")
else:
    content = file.read()
    print(content)
    file.close()

# try-except-finally
try:
    file = open("data.txt", "r")
    content = file.read()
    # 这里可能发生其他异常
except FileNotFoundError:
    print("文件不存在!")
finally:
    print("清理资源...")
    if 'file' in locals():
        file.close()  # 确保文件被关闭

7.2 自定义异常

python 复制代码
# 自定义异常类
class MyCustomError(Exception):
    """自定义异常"""
    def __init__(self, message, error_code):
        super().__init__(message)
        self.error_code = error_code
    
    def __str__(self):
        return f"[错误代码 {self.error_code}] {super().__str__()}"

# 使用自定义异常
def process_data(data):
    if not data:
        raise MyCustomError("数据不能为空", 1001)
    if len(data) < 5:
        raise MyCustomError("数据长度不足", 1002)
    return f"处理后的数据: {data}"

# 捕获自定义异常
try:
    result = process_data("")
except MyCustomError as e:
    print(f"自定义异常: {e}, 错误代码: {e.error_code}")

第八章:Python面向对象编程(OOP)

8.1 类与对象

python 复制代码
# 定义类
class Person:
    """人类"""
    
    # 类属性(所有实例共享)
    species = "Homo sapiens"
    
    def __init__(self, name, age):
        """构造方法,初始化实例属性"""
        self.name = name  # 实例属性
        self.age = age
    
    def greet(self):
        """实例方法"""
        return f"你好,我叫{self.name},今年{self.age}岁"
    
    @classmethod
    def create_baby(cls, name):
        """类方法"""
        return cls(name, 0)
    
    @staticmethod
    def is_adult(age):
        """静态方法"""
        return age >= 18

# 创建对象
alice = Person("Alice", 25)
print(alice.greet())  # 你好,我叫Alice,今年25岁

# 访问属性
print(alice.name)        # Alice
print(alice.species)     # Homo sapiens
print(Person.species)    # Homo sapiens

# 修改属性
alice.age = 26
Person.species = "Human"

# 使用类方法
baby = Person.create_baby("Baby Bob")
print(baby.greet())  # 你好,我叫Baby Bob,今年0岁

# 使用静态方法
print(Person.is_adult(20))  # True

8.2 继承与多态

python 复制代码
# 基类(父类)
class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        raise NotImplementedError("子类必须实现此方法")
    
    def move(self):
        return f"{self.name} 在移动"

# 子类继承
class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)  # 调用父类构造方法
        self.breed = breed
    
    def speak(self):  # 方法重写
        return f"{self.name} 说: 汪汪!"
    
    def fetch(self):  # 子类特有方法
        return f"{self.name} 在接球"

class Cat(Animal):
    def speak(self):
        return f"{self.name} 说: 喵喵!"

# 创建对象
dog = Dog("旺财", "金毛")
cat = Cat("咪咪")

print(dog.speak())  # 旺财 说: 汪汪!
print(cat.speak())  # 咪咪 说: 喵喵!
print(dog.move())   # 旺财 在移动
print(dog.fetch())  # 旺财 在接球

# 多态示例
animals = [Dog("小黑", "土狗"), Cat("小白")]
for animal in animals:
    print(animal.speak())

# 检查类型
print(isinstance(dog, Dog))      # True
print(isinstance(dog, Animal))   # True
print(issubclass(Dog, Animal))   # True

8.3 特殊方法(魔术方法)

python 复制代码
class Vector:
    """向量类"""
    
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    # 字符串表示
    def __str__(self):
        return f"Vector({self.x}, {self.y})"
    
    def __repr__(self):
        return f"Vector({self.x}, {self.y})"
    
    # 运算符重载
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)
    
    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)
    
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y
    
    # 容器方法
    def __len__(self):
        return 2
    
    def __getitem__(self, index):
        if index == 0:
            return self.x
        elif index == 1:
            return self.y
        else:
            raise IndexError("向量索引只能是0或1")
    
    # 上下文管理器
    def __enter__(self):
        print("进入向量上下文")
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("退出向量上下文")

# 使用特殊方法
v1 = Vector(2, 3)
v2 = Vector(4, 5)

print(v1)           # Vector(2, 3)
print(v1 + v2)      # Vector(6, 8)
print(v1 * 3)       # Vector(6, 9)
print(v1 == v2)     # False
print(len(v1))      # 2
print(v1[0])        # 2

# 使用上下文管理器
with Vector(1, 2) as v:
    print(f"在上下文中使用: {v}")

第九章:Python文件操作

9.1 文件读写

python 复制代码
# 写入文件
with open("example.txt", "w", encoding="utf-8") as file:
    file.write("第一行\n")
    file.write("第二行\n")
    file.write("第三行\n")

# 读取文件
with open("example.txt", "r", encoding="utf-8") as file:
    # 读取整个文件
    content = file.read()
    print("整个文件内容:")
    print(content)

# 逐行读取
with open("example.txt", "r", encoding="utf-8") as file:
    print("\n逐行读取:")
    for line in file:
        print(line.strip())  # strip()去除换行符

# 读取所有行到列表
with open("example.txt", "r", encoding="utf-8") as file:
    lines = file.readlines()
    print("\n所有行列表:")
    for i, line in enumerate(lines, 1):
        print(f"第{i}行: {line.strip()}")

# 追加模式
with open("example.txt", "a", encoding="utf-8") as file:
    file.write("追加的内容\n")

# 二进制文件
with open("image.jpg", "rb") as file:
    binary_data = file.read()

# 读写JSON文件
import json

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

# 写入JSON
with open("data.json", "w", encoding="utf-8") as file:
    json.dump(data, file, indent=2, ensure_ascii=False)

# 读取JSON
with open("data.json", "r", encoding="utf-8") as file:
    loaded_data = json.load(file)
    print(f"读取的数据: {loaded_data}")

第十章:Python最佳实践与技巧

10.1 Pythonic代码风格

python 复制代码
# 1. 列表推导式 vs 传统循环
# 传统方式
squares = []
for x in range(10):
    squares.append(x**2)

# Pythonic方式
squares = [x**2 for x in range(10)]

# 2. 多重赋值
# 传统方式
a = 1
b = 2
temp = a
a = b
b = temp

# Pythonic方式
a, b = 1, 2
a, b = b, a  # 交换变量

# 3. 使用enumerate获取索引
# 传统方式
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
    print(i, fruits[i])

# Pythonic方式
for i, fruit in enumerate(fruits):
    print(i, fruit)

# 4. 使用zip同时遍历多个列表
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

# 5. 使用with语句管理资源
# 传统方式(容易忘记关闭文件)
file = open("data.txt", "r")
try:
    content = file.read()
finally:
    file.close()

# Pythonic方式
with open("data.txt", "r") as file:
    content = file.read()

# 6. 使用get()方法访问字典
person = {"name": "Alice", "age": 25}

# 传统方式
if "city" in person:
    city = person["city"]
else:
    city = "Unknown"

# Pythonic方式
city = person.get("city", "Unknown")

# 7. 字符串连接
# 传统方式(低效)
result = ""
for s in ["a", "b", "c"]:
    result += s

# Pythonic方式
result = "".join(["a", "b", "c"])

# 8. 条件表达式
age = 20
# 传统方式
if age >= 18:
    status = "adult"
else:
    status = "minor"

# Pythonic方式
status = "adult" if age >= 18 else "minor"

10.2 调试技巧

python 复制代码
# 使用print调试
def calculate_sum(numbers):
    print(f"[DEBUG] 输入: {numbers}")  # 调试输出
    total = sum(numbers)
    print(f"[DEBUG] 输出: {total}")    # 调试输出
    return total

# 使用assert断言
def divide(a, b):
    assert b != 0, "除数不能为零"
    return a / b

# 使用logging模块
import logging

# 配置日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    filename='app.log'
)

def process_data(data):
    logging.info(f"开始处理数据: {data}")
    try:
        result = data * 2
        logging.info(f"处理完成,结果: {result}")
        return result
    except Exception as e:
        logging.error(f"处理失败: {e}")
        raise

# 使用pdb调试器
import pdb

def buggy_function():
    x = 1
    y = 0
    pdb.set_trace()  # 设置断点
    result = x / y   # 这里会出错
    return result

# 运行后进入pdb调试环境,可以:
# n - 执行下一行
# c - 继续执行
# q - 退出
# p 变量名 - 打印变量值
相关推荐
whm277719 小时前
Visual Basic 键盘事件
开发语言·visual studio
飞Link19 小时前
【模型与算法】Isolation Forest、Local Outlier Factor、One-Class SVM 三者系统对比与实战指南
人工智能·python·机器学习·数据挖掘
计算衎19 小时前
Python的FastAPI,Flask,Django Web框架的区别
python·django·flask·fastapi
上不如老下不如小19 小时前
2025年第七届全国高校计算机能力挑战赛 决赛 Java组 编程题汇总
java·python·算法
渔舟唱晚@19 小时前
从原理到实现:基于 Y.js 和 Tiptap 的实时在线协同编辑器全解析
开发语言·javascript·编辑器
Boop_wu19 小时前
[Java EE] 网络编程套接字
开发语言·单片机·php
亮子AI19 小时前
chart.js 雷达图顶部标题怎样消除?
开发语言·前端·javascript·chart.js
兩尛19 小时前
查找接口成功率最优时间段 (c卷)
c语言·开发语言·算法
再__努力1点19 小时前
【59】3D尺度不变特征变换(SIFT3D):医学影像关键点检测的核心算法与实现
人工智能·python·算法·计算机视觉·3d