Python 基础知识
一、Python 概述
1.1 什么是 Python
Python 是一种高级的、解释型的、面向对象的编程语言,具有简洁的语法和强大的功能。
核心特点:
- 语法简洁,易于学习
- 跨平台(Windows、macOS、Linux)
- 丰富的标准库和第三方库
- 支持多种编程范式(面向对象、函数式)
- 动态类型
1.2 Python 版本
| 版本 | 说明 |
|---|---|
| Python 2 | 已停止维护(2020年) |
| Python 3 | 当前主流版本(推荐 3.8+) |
1.3 应用领域
- Web 开发(Django、Flask)
- 数据科学(NumPy、Pandas)
- 人工智能(TensorFlow、PyTorch)
- 自动化脚本
- 网络爬虫
二、环境搭建
2.1 安装 Python
bash
# macOS
brew install python3
# Linux
sudo apt-get install python3
# Windows
# 从官网下载安装包:https://www.python.org/
2.2 验证安装
bash
python3 --version
# Python 3.10.0
python3
# 进入交互式环境
2.3 虚拟环境
bash
# 创建虚拟环境
python3 -m venv venv
# 激活虚拟环境
# macOS/Linux
source venv/bin/activate
# Windows
venv\Scripts\activate
# 退出虚拟环境
deactivate
# 安装包
pip install package_name
# 导出依赖
pip freeze > requirements.txt
# 安装依赖
pip install -r requirements.txt
三、基础语法
3.1 注释
python
# 单行注释
"""
多行注释
可以写多行
"""
'''
这也是多行注释
'''
3.2 变量和数据类型
python
# 变量(无需声明类型)
name = "zhangsan"
age = 25
height = 175.5
is_student = True
# 数据类型
type(name) # <class 'str'>
type(age) # <class 'int'>
type(height) # <class 'float'>
type(is_student) # <class 'bool'>
3.3 基本数据类型
python
# 数字
num_int = 10 # 整数
num_float = 3.14 # 浮点数
num_complex = 3 + 4j # 复数
# 字符串
str1 = "单引号"
str2 = '双引号'
str3 = """多行
字符串"""
str4 = f"格式化字符串 {name}"
# 布尔值
is_true = True
is_false = False
# None
value = None
3.4 类型转换
python
# 转整数
int("123") # 123
int(3.14) # 3
# 转浮点数
float("3.14") # 3.14
float(10) # 10.0
# 转字符串
str(123) # "123"
str(3.14) # "3.14"
# 转布尔值
bool(1) # True
bool(0) # False
bool("") # False
bool("hello") # True
四、运算符
4.1 算术运算符
python
a, b = 10, 3
a + b # 13
a - b # 7
a * b # 30
a / b # 3.333...
a // b # 3 (整除)
a % b # 1 (取余)
a ** b # 1000 (幂运算)
4.2 比较运算符
python
10 > 5 # True
10 < 5 # False
10 >= 5 # True
10 <= 5 # False
10 == 5 # False
10 != 5 # True
4.3 逻辑运算符
python
True and True # True
True and False # False
True or False # True
False or False # False
not True # False
not False # True
4.4 赋值运算符
python
x = 10
x += 5 # x = x + 5
x -= 5 # x = x - 5
x *= 2 # x = x * 2
x /= 2 # x = x / 2
x //= 3 # x = x // 3
x %= 3 # x = x % 3
x **= 2 # x = x ** 2
4.5 成员运算符
python
"a" in "abc" # True
"d" not in "abc" # True
1 in [1, 2, 3] # True
五、数据结构
5.1 列表(List)
python
# 创建列表
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
# 访问元素
fruits[0] # "apple"
fruits[-1] # "orange" (最后一个)
# 切片
fruits[0:2] # ["apple", "banana"]
fruits[:2] # ["apple", "banana"]
fruits[1:] # ["banana", "orange"]
fruits[::-1] # 反转列表
# 修改
fruits[0] = "grape"
fruits.append("mango") # 末尾添加
fruits.insert(1, "pear") # 指定位置插入
fruits.extend(["kiwi"]) # 扩展列表
# 删除
fruits.remove("banana") # 删除指定值
fruits.pop() # 删除最后一个
fruits.pop(0) # 删除指定索引
del fruits[0] # 删除指定索引
# 其他操作
len(fruits) # 长度
fruits.count("apple") # 计数
fruits.index("banana") # 索引
fruits.sort() # 排序
fruits.reverse() # 反转
5.2 元组(Tuple)
python
# 创建元组(不可变)
point = (10, 20)
colors = ("red", "green", "blue")
single = (1,) # 单个元素需要逗号
# 访问元素
point[0] # 10
point[1] # 20
# 解包
x, y = point
# 元组不可修改
# point[0] = 5 # 错误
5.3 字典(Dictionary)
python
# 创建字典
person = {
"name": "zhangsan",
"age": 25,
"city": "Beijing"
}
# 访问
person["name"] # "zhangsan"
person.get("name") # "zhangsan"
person.get("email", "N/A") # 默认值
# 修改
person["age"] = 26
person["email"] = "test@example.com"
# 删除
del person["email"]
person.pop("age")
person.popitem() # 删除最后一个
# 遍历
for key in person:
print(key, person[key])
for key, value in person.items():
print(key, value)
# 其他操作
person.keys() # 所有键
person.values() # 所有值
person.items() # 所有键值对
len(person) # 长度
5.4 集合(Set)
python
# 创建集合(无序、不重复)
numbers = {1, 2, 3, 4, 5}
colors = set(["red", "green", "blue"])
# 添加
numbers.add(6)
numbers.update([7, 8])
# 删除
numbers.remove(1) # 不存在会报错
numbers.discard(1) # 不存在不报错
numbers.pop() # 随机删除一个
# 集合运算
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1 | set2 # 并集 {1, 2, 3, 4, 5}
set1 & set2 # 交集 {3}
set1 - set2 # 差集 {1, 2}
set1 ^ set2 # 对称差集 {1, 2, 4, 5}
六、控制流
6.1 条件语句
python
# if-elif-else
age = 20
if age < 18:
print("未成年")
elif age < 60:
print("成年人")
else:
print("老年人")
# 三元运算符
status = "成年" if age >= 18 else "未成年"
6.2 循环语句
python
# for 循环
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# 带索引
for index, fruit in enumerate(fruits):
print(index, fruit)
# range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for i in range(1, 10, 2):
print(i) # 1, 3, 5, 7, 9
# while 循环
count = 0
while count < 5:
print(count)
count += 1
# 循环控制
for i in range(10):
if i == 5:
break # 跳出循环
if i == 3:
continue # 跳过本次循环
print(i)
6.3 列表推导式
python
# 基本语法
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 带条件
evens = [x for x in range(10) if x % 2 == 0]
# [0, 2, 4, 6, 8]
# 嵌套
matrix = [[i*j for j in range(3)] for i in range(3)]
# [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
# 字典推导式
squares_dict = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 集合推导式
squares_set = {x**2 for x in range(5)}
# {0, 1, 4, 9, 16}
七、函数
7.1 函数定义
python
# 基本函数
def greet():
print("Hello")
# 带参数
def greet(name):
print(f"Hello, {name}")
# 默认参数
def greet(name="Guest"):
print(f"Hello, {name}")
# 关键字参数
def greet(name, age, city="Beijing"):
print(f"{name}, {age}, {city}")
greet(name="zhangsan", age=25)
# 可变参数
def sum_numbers(*args):
return sum(args)
sum_numbers(1, 2, 3, 4) # 10
# 关键字可变参数
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="zhangsan", age=25)
7.2 返回值
python
def add(a, b):
return a + b
result = add(3, 5) # 8
# 多返回值
def get_name_age():
return "zhangsan", 25
name, age = get_name_age()
7.3 Lambda 函数
python
# 匿名函数
square = lambda x: x**2
square(5) # 25
# 与 map、filter 使用
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
# [1, 4, 9, 16, 25]
evens = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4]
7.4 装饰器
python
# 简单装饰器
def my_decorator(func):
def wrapper():
print("函数执行前")
func()
print("函数执行后")
return wrapper
@my_decorator
def say_hello():
print("Hello")
say_hello()
# 带参数的装饰器
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}")
greet("zhangsan")
八、面向对象
8.1 类和对象
python
# 定义类
class Person:
# 类属性
species = "Homo sapiens"
# 构造方法
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
# 实例方法
def introduce(self):
return f"I'm {self.name}, {self.age} years old"
# 类方法
@classmethod
def from_birth_year(cls, name, birth_year):
age = 2024 - birth_year
return cls(name, age)
# 静态方法
@staticmethod
def is_adult(age):
return age >= 18
# 创建对象
person = Person("zhangsan", 25)
print(person.introduce())
# 使用类方法
person2 = Person.from_birth_year("lisi", 2000)
8.2 继承
python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def speak(self):
return f"{self.name} barks"
dog = Dog("Buddy", "Golden Retriever")
print(dog.speak())
8.3 封装和属性
python
class Person:
def __init__(self, name, age):
self._name = name # 受保护
self.__age = age # 私有
# 属性访问器
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if isinstance(value, str):
self._name = value
else:
raise ValueError("Name must be a string")
@property
def age(self):
return self.__age
person = Person("zhangsan", 25)
print(person.name) # 使用属性
person.name = "lisi" # 使用 setter
九、文件操作
9.1 文件读写
python
# 写入文件
with open("file.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!\n")
f.write("第二行\n")
# 读取文件
with open("file.txt", "r", encoding="utf-8") as f:
content = f.read() # 读取全部
lines = f.readlines() # 读取所有行
line = f.readline() # 读取一行
# 逐行读取
with open("file.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())
# 追加模式
with open("file.txt", "a", encoding="utf-8") as f:
f.write("追加内容\n")
9.2 JSON 操作
python
import json
# 写入 JSON
data = {
"name": "zhangsan",
"age": 25,
"city": "Beijing"
}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# 读取 JSON
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
# 字符串转换
json_str = json.dumps(data)
data = json.loads(json_str)
十、异常处理
10.1 try-except
python
# 基本异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("除零错误")
# 多个异常
try:
result = int("abc")
except ValueError:
print("值错误")
except TypeError:
print("类型错误")
except Exception as e:
print(f"其他错误: {e}")
# else 和 finally
try:
result = 10 / 2
except ZeroDivisionError:
print("错误")
else:
print("没有错误")
finally:
print("总是执行")
10.2 抛出异常
python
# 抛出异常
def divide(a, b):
if b == 0:
raise ValueError("除数不能为零")
return a / b
# 自定义异常
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
raise CustomError("自定义错误")
十一、模块和包
11.1 导入模块
python
# 导入整个模块
import math
result = math.sqrt(16)
# 导入特定函数
from math import sqrt, pi
result = sqrt(16)
# 导入所有(不推荐)
from math import *
# 别名
import numpy as np
from datetime import datetime as dt
11.2 创建模块
python
# my_module.py
def greet(name):
return f"Hello, {name}"
def add(a, b):
return a + b
# 使用
import my_module
my_module.greet("zhangsan")
11.3 包
markdown
my_package/
├── __init__.py
├── module1.py
└── module2.py
python
# 使用包
from my_package import module1
from my_package.module2 import function
十二、常用标准库
12.1 os 模块
python
import os
# 路径操作
os.getcwd() # 当前目录
os.chdir("/path") # 切换目录
os.listdir(".") # 列出文件
# 文件操作
os.path.exists("file.txt") # 文件是否存在
os.path.join("dir", "file") # 路径拼接
os.path.abspath("file.txt") # 绝对路径
12.2 datetime 模块
python
from datetime import datetime, date, timedelta
# 当前时间
now = datetime.now()
today = date.today()
# 格式化
now.strftime("%Y-%m-%d %H:%M:%S")
datetime.strptime("2024-01-26", "%Y-%m-%d")
# 时间计算
tomorrow = today + timedelta(days=1)
12.3 random 模块
python
import random
random.random() # 0-1 随机数
random.randint(1, 10) # 1-10 随机整数
random.choice([1, 2, 3]) # 随机选择
random.shuffle([1, 2, 3]) # 打乱列表
12.4 re 模块(正则表达式)
python
import re
# 匹配
pattern = r"\d+"
text = "abc123def456"
matches = re.findall(pattern, text) # ['123', '456']
# 替换
re.sub(r"\d+", "NUM", text) # "abcNUMdefNUM"
# 分割
re.split(r"\d+", text) # ['abc', 'def', '']
十三、常用第三方库
13.1 requests(HTTP 请求)
python
import requests
# GET 请求
response = requests.get("https://api.example.com/data")
data = response.json()
# POST 请求
response = requests.post(
"https://api.example.com/data",
json={"key": "value"},
headers={"Authorization": "Bearer token"}
)
13.2 pandas(数据处理)
python
import pandas as pd
# 读取数据
df = pd.read_csv("data.csv")
df = pd.read_excel("data.xlsx")
# 数据操作
df.head() # 前5行
df.info() # 信息
df.describe() # 统计信息
df.groupby("column").sum()
13.3 numpy(数值计算)
python
import numpy as np
# 创建数组
arr = np.array([1, 2, 3, 4, 5])
matrix = np.array([[1, 2], [3, 4]])
# 数组操作
arr.mean() # 平均值
arr.sum() # 求和
arr.max() # 最大值
np.dot(matrix1, matrix2) # 矩阵乘法
十四、Web 开发基础
14.1 Flask
python
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, World!"
@app.route("/api/user", methods=["GET", "POST"])
def user():
if request.method == "POST":
data = request.json
return jsonify({"status": "success"})
return jsonify({"name": "zhangsan", "age": 25})
if __name__ == "__main__":
app.run(debug=True)
14.2 Django 基础
python
# views.py
from django.http import JsonResponse
def hello(request):
return JsonResponse({"message": "Hello, World!"})
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path("hello/", views.hello),
]
十五、最佳实践
15.1 代码规范(PEP 8)
python
# ✅ 命名规范
# 变量和函数:snake_case
user_name = "zhangsan"
def get_user_name():
pass
# 类名:PascalCase
class UserProfile:
pass
# 常量:UPPER_CASE
MAX_SIZE = 100
# ✅ 缩进:4个空格
if condition:
do_something()
# ✅ 行长度:不超过79字符
long_string = (
"这是一个很长的字符串"
"可以分行写"
)
15.2 文档字符串
python
def add(a, b):
"""
计算两个数的和
Args:
a: 第一个数
b: 第二个数
Returns:
两个数的和
"""
return a + b
15.3 类型提示
python
from typing import List, Dict, Optional
def process_data(
items: List[str],
config: Optional[Dict[str, int]] = None
) -> Dict[str, int]:
"""处理数据"""
return {}
十六、推荐资源
官方文档:
- Python 官网:www.python.org/
- Python 文档:docs.python.org/zh-cn/3/
学习资源:
- 《Python 编程:从入门到实践》
- 《流畅的 Python》
- Python 教程:www.runoob.com/python3/pyt...
- Real Python:realpython.com/
十七、总结
Python 核心要点:
简洁语法 + 丰富库 + 多范式 + 跨平台 = 高效开发
核心心法:
Python 的简洁性让开发更高效。 掌握数据结构、函数和面向对象是 Python 开发的基础。
📝 文档信息
- 作者: 阿鑫
- 更新日期: 2026.3