Python 是一种高级、解释型、通用的编程语言,因其代码的可读性和简洁性而广受欢迎。它适用于多种应用场景,包括网站开发、数据分析、人工智能、自动化脚本、科学计算等。
主要特点
-
简单易学的语法
-
跨平台兼容性
-
丰富的标准库
-
支持多种编程范式(面向对象、函数式、过程式)
-
动态类型
-
自动内存管理
【官方文档】:3.13.5 Documentation
1. 基础语法
1.1 变量与数据类型
# 变量定义
x = 10 # 整数
y = 3.14 # 浮点数
name = "Alice" # 字符串
is_active = True # 布尔值
# 类型转换
int("123") # 字符串转整数
float("3.14") # 字符串转浮点数
str(123) # 数字转字符串
1.2 输入输出
# 输出
print("Hello, World!") # 打印字符串
print(f"Value: {x}") # f-string格式化 (Python 3.6+)
# 输入
name = input("Enter your name: ")
age = int(input("Enter your age: "))
2. 运算符
2.1 算术运算符
a + b # 加法
a - b # 减法
a * b # 乘法
a / b # 除法(浮点结果)
a // b # 整除
a % b # 取模
a ** b # 幂运算
2.2 比较运算符
a == b # 等于
a != b # 不等于
a > b # 大于
a < b # 小于
a >= b # 大于等于
a <= b # 小于等于
2.3 逻辑运算符
x and y # 与
x or y # 或
not x # 非
3. 控制结构
3.1 条件语句
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
3.2 循环语句
# while循环
while x > 0:
print(x)
x -= 1
# for循环
for i in range(5): # 0到4
print(i)
for item in [1, 2, 3]: # 遍历列表
print(item)
# 循环控制
break # 退出循环
continue # 跳过当前迭代
4. 数据结构
4.1 列表(List)
my_list = [1, 2, 3, "a", "b"]
my_list[0] # 访问元素(索引从0开始)
my_list.append(4) # 添加元素
my_list.remove(2) # 删除元素
len(my_list) # 列表长度
4.2 元组(Tuple)
my_tuple = (1, 2, 3) # 不可变序列
4.3 字典(Dictionary)
my_dict = {"name": "Alice", "age": 25}
my_dict["name"] # 访问值
my_dict["age"] = 26 # 修改值
my_dict["city"] = "NY" # 添加新键值对
"name" in my_dict # 检查键是否存在
4.4 集合(Set)
my_set = {1, 2, 3}
my_set.add(4) # 添加元素
my_set.remove(2) # 删除元素
5. 函数
5.1 定义与调用
def greet(name):
"""函数文档字符串"""
return f"Hello, {name}!"
result = greet("Alice")
5.2 参数类型
# 默认参数
def power(x, n=2):
return x ** n
# 关键字参数
power(n=3, x=2)
# 可变参数
def sum_all(*args):
return sum(args)
# 关键字可变参数
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
6. 文件操作
# 读取文件
with open("file.txt", "r") as f:
content = f.read()
# 写入文件
with open("output.txt", "w") as f:
f.write("Hello, World!")
7. 异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print(f"An error occurred: {e}")
else:
print("No errors")
finally:
print("This always executes")
8. 面向对象编程
class Person:
# 类属性
species = "Homo sapiens"
# 构造方法
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
# 实例方法
def greet(self):
return f"Hello, my name is {self.name}"
# 类方法
@classmethod
def from_birth_year(cls, name, birth_year):
age = 2023 - birth_year
return cls(name, age)
# 静态方法
@staticmethod
def is_adult(age):
return age >= 18
# 继承
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
9. 模块与包
# 导入模块
import math
from math import sqrt
import numpy as np
# 创建模块
# 在my_module.py中定义函数,然后:
# import my_module
# my_module.my_function()
10. 常用内置函数
len(obj) # 返回对象长度
range(stop) # 生成数字序列
type(obj) # 返回对象类型
isinstance(obj, class) # 检查对象类型
abs(x) # 绝对值
sum(iterable) # 求和
max(iterable) # 最大值
min(iterable) # 最小值
sorted(iterable) # 排序
enumerate(iterable) # 添加索引
zip(iter1, iter2) # 并行迭代
11. 列表推导式与生成器
# 列表推导式
squares = [x**2 for x in range(10) if x % 2 == 0]
# 字典推导式
square_dict = {x: x**2 for x in range(5)}
# 生成器表达式
gen = (x**2 for x in range(10))
12. Lambda函数
# 匿名函数
square = lambda x: x ** 2
sorted(names, key=lambda x: len(x)) # 按长度排序
13. 装饰器
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@my_decorator
def say_hello():
print("Hello!")
14. 常用标准库
import os # 操作系统接口
import sys # 系统相关功能
import re # 正则表达式
import json # JSON处理
import datetime # 日期时间
import random # 随机数
import itertools # 迭代工具
import collections # 扩展容器类型
15. 虚拟环境与包管理
# 创建虚拟环境
python -m venv myenv
# 激活虚拟环境
# Windows: myenv\Scripts\activate
# Unix/macOS: source myenv/bin/activate
# 安装包
pip install package_name
# 导出环境
pip freeze > requirements.txt
# 从文件安装
pip install -r requirements.txt