Python 基础语法笔记:从入门到进阶的系统学习
本文系统整理了 Python 语言的核心知识,包括 Python 2/3 差异、环境管理、基础语法、数据类型、函数式编程特性、面向对象编程、异常处理等内容,适合有其他语言基础、想快速上手 Python 的开发者参考。
一、Python 环境搭建
1.1 pyenv 版本管理
编译安装 Python 步骤繁琐,推荐使用 pyenv 来方便地安装和切换 Python 版本(类似于 Go 的 goup、GCC 的 scl)。
Linux 安装步骤:
bash
# 安装依赖
sudo yum -y install git gcc zlib-devel bzip2 bzip2-devel \
readline-devel sqlite sqlite-devel openssl-devel \
xz xz-devel libffi-devel
# 安装 pyenv
curl https://pyenv.run | bash
配置环境变量: 在 ~/.bashrc 或 ~/.bash_profile 中添加:
bash
export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init --path)"
eval "$(pyenv virtualenv-init -)"
安装和使用 Python 版本:
bash
# 安装指定版本
pyenv install 3.9.1
# 全局启用
pyenv global 3.9.1
# 验证
python --version
1.2 pip 包管理器与镜像配置
pip 是 Python 的包管理器(Package Installer for Python),安装 Python 后 pip 也会随之安装。
配置国内镜像源(加速下载):
bash
# 方式一:直接执行命令
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
# 方式二:手动创建配置文件
配置文件位置:
- Linux:
~/.pip/pip.conf(没有则创建) - Windows:
C:\Users\<用户名>\pip\pip.ini(没有则创建)
ini
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host = mirrors.aliyun.com
二、Python 2 与 Python 3 的关键差异
Python 2 和 Python 3 存在一些不兼容的差异,了解这些对于维护遗留代码和理解 Python 演进很有帮助:
| 特性 | Python 2 | Python 3 |
|---|---|---|
| print 语句 | print "hello" |
print("hello") |
| 整数除法 | 3/2 = 1(整数除法) |
3/2 = 1.5,3//2 = 1 |
| 字符串编码 | ASCII(需 # coding=utf-8) |
默认 UTF-8 |
| range | 返回列表 | 返回迭代器 |
| 异常语法 | except Exception, e |
except Exception as e |
| 类 | 经典类和新式类 | 只有新式类 |
| input | raw_input() |
input() |
编码声明(Python 2):
python
# -*- coding: utf-8 -*-
# 将默认 ASCII 编码改为 UTF-8,支持中文
三、基础语法
3.1 缩进与代码块
Python 最大的特点是使用缩进 (而非花括号 {})来控制类、函数和逻辑判断的语句段。同一语句块的缩进长度必须相同:
python
if True:
print("true")
else:
print("false")
注意: 如果缩进长度不一致或者混用空格和 Tab,会报 IndentationError(缩进错误)。建议统一使用 4 个空格缩进。
代码组(子句): 像 if、while、def 和 class 这样的复合语句,首行以关键字开始,以冒号 : 结束,之后的代码构成一个代码组。
3.2 多行语句与注释
python
# 使用反斜杠续行
total = item_one + \
item_two + \
item_three
# 在 ()、[]、{} 中的多行语句不需要续行符
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
# 单行注释
# 这是一条注释
"""
多行注释(三引号)
可以包含多行内容
常用作函数或类的文档字符串(docstring)
"""
3.3 字符串
Python 中字符串可以使用单引号、双引号和三引号:
python
# 单引号和双引号等价
s1 = 'Hello'
s2 = "World"
# 三引号可包含多行内容
text = """This is a segment
first line
second line"""
# 字符串操作
str = "Hello World"
print(str[0]) # H
print(str[1:6]) # ello
print(str * 2) # Hello WorldHello World
3.4 同行多语句与命令行参数
python
# 同一行中使用多条语句,用分号分隔
import sys; x = 'hello'; sys.stdout.write(x + '\n')
# 获取命令行参数
import sys
for i in range(len(sys.argv)):
print(sys.argv[i])
# python test.py arg1 arg2
# 输出: test.py arg1 arg2
3.5 执行 Shell 命令
python
import os
import subprocess
# 方式一:os.system --- 只返回执行状态(0 或 1)
os.system('cat /proc/cpuinfo')
# 方式二:os.popen --- 返回输出对象,需 read() 取出结果
output = os.popen('cat /proc/cpuinfo')
print(output.read())
# 方式三:subprocess(推荐,Python 3)
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)
四、数据类型
4.1 五种标准数据类型
Python 有五个标准的数据类型:
1. Numbers(数字)
python
# int(整型)
a = 20
# float(浮点型)
b = 3.14
# complex(复数)
c = 3 + 4j
# 类型检查
print(type(a)) # <class 'int'>
print(isinstance(b, float)) # True
特殊说明: Python 中数字类型是不可变类型。a = 20; b = 20 时,a 与 b 指向同一内存地址(小整数缓存机制),这与 C 语言有本质区别。
2. String(字符串)
python
str = "Hello World"
# 下标取值和切片
print(str[1]) # e
print(str[1:6]) # ello (注意:不包含索引6的字符)
print(str[:5]) # Hello
print(str[6:]) # World
print(str * 2) # Hello WorldHello World
3. List(列表)
列表类似于其他语言的数组,但更灵活,支持不同类型元素的混合存储:
python
# 创建列表
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
# 基本操作
fruits.append("orange") # 追加元素
fruits.pop() # 弹出最后一个元素
fruits.insert(1, "grape") # 在指定位置插入
fruits.remove("banana") # 删除指定元素
4. Tuple(元组)
元组与列表类似,但元素不能修改(只读),用圆括号定义:
python
# 创建元组
tup = ("apple", "banana", "cherry")
single = (42,) # 单元素元组,注意逗号
# 元组支持索引和切片
print(tup[0]) # apple
print(tup[1:]) # ('banana', 'cherry')
5. Dictionary(字典)
字典是一种键值对集合,通过键(key)来快速检索数据:
python
# 创建字典
person = {
"name": "Zhang San",
"age": 25,
"city": "Beijing"
}
# 访问和修改
print(person["name"]) # Zhang San
person["age"] = 26 # 修改值
person["email"] = "a@b.com" # 添加新键值对
# 遍历
for key, value in person.items():
print(f"{key}: {value}")
# 删除
del person["city"]
五种类型对比:
| 类型 | 定义方式 | 可读写 | 访问方式 |
|---|---|---|---|
| 列表 List | [] |
可读写 | 下标/偏移 |
| 元组 Tuple | () 或 , |
只读 | 下标/偏移 |
| 字典 Dict | {} |
可读写 | 键(key) |
4.2 集合(Set)--- Python 3 重点
集合是一个无序不重复元素的序列,常用于成员关系测试和去重:
python
# 创建集合
a = {"apple", "banana", "cherry"}
b = set("hello") # {'h', 'e', 'l', 'o'},注意去重
# 空集合必须用 set(),不能用 {}(那是空字典)
empty = set()
# 成员测试
if "apple" in a:
print("found")
# 集合运算
c = {1, 2, 3, 4}
d = {3, 4, 5, 6}
print(c | d) # 并集: {1, 2, 3, 4, 5, 6}
print(c & d) # 交集: {3, 4}
print(c - d) # 差集: {1, 2}
print(c ^ d) # 对称差集: {1, 2, 5, 6}
4.3 可变与不可变对象
这是理解 Python 参数传递的关键:
- 不可变类型:
int、float、string、tuple。变量赋值a = 5后再a = 10,实际是新生成一个 int 值对象 10,再让 a 指向它,5 被丢弃。 - 可变类型:
list、dict、set。变量赋值la = [1,2,3]后la[2] = 5,是修改了列表内部的值,列表本身不变。
python
# 不可变对象
a = 5
b = a
a = 10
print(b) # 5(b 不受影响)
# 可变对象
la = [1, 2, 3]
lb = la
la[0] = 99
print(lb) # [99, 2, 3](lb 跟着变了)
五、运算符
5.1 基本运算符
Python 的运算符大部分和 C 语言类似,以下是特殊之处:
python
# 算术运算符
print(2 ** 3) # 8(幂运算)
print(9 // 2) # 4(整除,返回商的整数部分)
# 比较运算符
print(1 != 2) # True
# Python 2 还有 <> 运算符表示不等于,Python 3 已移除
# 逻辑运算符(用英文单词,不是符号)
print(True and False) # False
print(True or False) # True
print(not True) # False
5.2 特有运算符
成员运算符:
python
list = [1, 2, 3, 4, 5]
print(4 in list) # True
print(6 not in list) # True
身份运算符:
python
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a is c) # True(同一对象)
print(a is b) # False(不同对象,即使值相同)
print(a == b) # True(值相等)
# id() 返回变量的内存地址
print(id(a)) # 类似 140234567890
is 与 == 的区别:
is判断两个变量是否引用同一个对象(比较内存地址)==判断引用变量的值是否相等
六、函数
6.1 函数定义与参数
python
# 基本函数定义
def greet(name):
print(f"Hello, {name}!")
# 默认参数
def printinfo(name, age=35):
print(f"Name: {name}, Age: {age}")
# 可变参数
def func(argv, *args):
print(argv)
for var in args:
print(var)
func("first", 1, 2, 3, 4)
# 输出: first 1 2 3 4
6.2 匿名函数 lambda
python
# lambda 表达式
square = lambda x: x ** 2
print(square(5)) # 25
# 常与 map、filter 等配合使用
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4]
6.3 参数传递:可变 vs 不可变对象
python
# 传不可变对象(类似 C++ 值传递)
def change_int(a):
a = 10
x = 5
change_int(x)
print(x) # 5(不受影响)
# 传可变对象(类似 C++ 引用传递)
def change_list(la):
la.append(4)
mylist = [1, 2, 3]
change_list(mylist)
print(mylist) # [1, 2, 3, 4](被修改了)
七、列表推导式
列表推导式是 Python 最优雅的特性之一,可以用简洁的语法从已有列表创建新列表:
python
# 基本形式
vec = [2, 4, 6]
doubled = [3 * x for x in vec]
print(doubled) # [6, 12, 18]
# 带条件的推导式
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# 嵌套推导式
pairs = [[x, x**2] for x in vec]
print(pairs) # [[2, 4], [4, 16], [6, 36]]
# 构建列表
squares = [i**2 for i in range(1, 11)]
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 字典推导式
word = "hello"
char_count = {c: word.count(c) for c in set(word)}
print(char_count) # {'h': 1, 'e': 1, 'l': 2, 'o': 1}
八、迭代器与生成器
8.1 迭代器
迭代器是一个可以记住遍历位置的对象,只能往前不会后退:
python
# 创建迭代器
list_data = [1, 2, 3, 4]
it = iter(list_data)
# 逐个获取元素
print(next(it)) # 1
print(next(it)) # 2
# 使用 for 循环遍历
for item in it:
print(item) # 3, 4
8.2 生成器
使用了 yield 的函数被称为生成器(Generator)。生成器是一个返回迭代器的函数,每次遇到 yield 时函数会暂停并保存运行信息,返回 yield 的值:
python
# 使用 yield 实现斐波那契数列
def fibonacci(n):
a, b = 0, 1
count = 0
while count < n:
yield a
a, b = b, a + b
count += 1
# 使用生成器
for num in fibonacci(10):
print(num, end=" ")
# 输出: 0 1 1 2 3 5 8 13 21 34
# 生成器表达式(类似列表推导式,但用圆括号)
gen = (x**2 for x in range(10))
for val in gen:
print(val, end=" ")
生成器的优势: 不会一次性将所有元素加载到内存中,非常适合处理大数据集合。
九、面向对象编程
9.1 类的定义
python
class Person:
"""一个简单的类示例"""
# 类变量
count = 0
def __init__(self, name, age):
"""构造函数"""
self.name = name # 公有属性
self.age = age # 公有属性
self.__weight = 0 # 私有属性(双下划线开头)
Person.count += 1
def display(self):
"""实例方法"""
print(f"Name: {self.name}, Age: {self.age}")
def get_weight(self):
"""通过方法访问私有属性"""
return self.__weight
def set_weight(self, weight):
self.__weight = weight
self 关键字: self 代表类的实例(类似 C++ 的 this 指针),是方法的第一个参数。self 不是 Python 关键字,但按惯例使用这个名字。
9.2 继承
python
class Student(Person):
"""继承 Person 类"""
def __init__(self, name, age, grade):
# 调用父类构造函数
super().__init__(name, age)
self.grade = grade
def display(self):
"""重写父类方法"""
super().display()
print(f"Grade: {self.grade}")
注意: 如果基类中有相同的方法名,Python 从左至右搜索,即方法在子类中未找到时,从左到右查找基类中是否包含方法。
9.3 私有属性与方法
python
class MyClass:
__private_var = 0 # 私有属性
def __private_method(self): # 私有方法
print("This is private")
def public_method(self):
self.__private_method() # 类内部可以调用
9.4 类的专有方法(魔术方法)
python
class MyNumber:
def __init__(self, value):
self.value = value
def __str__(self): # print() 时调用
return str(self.value)
def __add__(self, other): # + 运算符
return MyNumber(self.value + other.value)
def __len__(self): # len() 函数
return abs(self.value)
def __eq__(self, other): # == 运算符
return self.value == other.value
常用魔术方法:
| 方法 | 触发时机 |
|---|---|
__init__ |
构造函数,创建对象时调用 |
__del__ |
析构函数,对象被销毁时调用 |
__str__ |
str() 或 print() 时调用 |
__repr__ |
交互式解释器中的表示 |
__len__ |
len() 函数调用 |
__getitem__ / __setitem__ |
索引访问 |
__add__ / __sub__ / __mul__ |
算术运算符 |
__call__ |
对象作为函数调用 |
十、异常处理
10.1 try-except 基本用法
python
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again.")
try 语句工作流程:
- 执行 try 子句
- 如果没有异常,跳过 except 子句
- 如果发生异常,跳过 try 余下部分,匹配 except 子句
- 如果异常没有匹配任何 except,传递到上层 try
10.2 多种异常处理
python
# 同时处理多种异常
try:
result = 10 / 0
except (TypeError, ZeroDivisionError) as e:
print(f"Error: {e}")
# 多个 except 子句
try:
f = open("file.txt")
content = f.read()
except FileNotFoundError:
print("File not found")
except PermissionError:
print("Permission denied")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
# 无论是否发生异常都会执行
print("Cleanup done")
10.3 抛出异常
python
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
十一、常用标准库
11.1 模块导入
python
# 导入整个模块
import os
# 从模块中导入特定函数
from os import path
# 导入多个函数
from sys import argv, exit
# 导入所有(不推荐)
from os import *
11.2 正则表达式(re 模块)
python
import re
# match:从字符串开头匹配
result = re.match("Hello", "Hello World")
print(result) # <re.Match object>(匹配成功)
result = re.match("World", "Hello World")
print(result) # None(开头不匹配)
# search:搜索整个字符串
result = re.search("World", "Hello World")
print(result) # <re.Match object>(找到匹配)
match vs search 的区别:
match只从字符串的开头匹配search搜索字符串的所有位置
11.3 时间处理(time 模块)
python
import time
from datetime import datetime
# 获取时间戳(距离 1970-01-01 的秒数)
timestamp = time.time()
# 时间戳转结构体
local_time = time.localtime(timestamp)
print(local_time.tm_year) # 年
print(local_time.tm_mon) # 月
print(local_time.tm_mday) # 日
# 格式化时间
formatted = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
print(formatted)
# datetime 更方便
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
struct_time 元组结构:
| 索引 | 属性 | 含义 |
|---|---|---|
| 0 | tm_year | 年 |
| 1 | tm_mon | 月(1-12) |
| 2 | tm_mday | 日(1-31) |
| 3 | tm_hour | 时(0-23) |
| 4 | tm_min | 分(0-59) |
| 5 | tm_sec | 秒(0-61) |
| 6 | tm_wday | 星期(0-6) |
| 7 | tm_yday | 一年中第几天 |
| 8 | tm_isdst | 是否夏令时 |
11.4 数据类型转换
python
# 类型转换函数
int("123") # 字符串转整数: 123
float("3.14") # 字符串转浮点: 3.14
str(123) # 数字转字符串: "123"
list("hello") # 字符串转列表: ['h', 'e', 'l', 'l', 'o']
tuple([1,2,3]) # 列表转元组: (1, 2, 3)
set([1,2,2,3]) # 列表转集合: {1, 2, 3}
dict(a=1, b=2) # 创建字典: {'a': 1, 'b': 2}
十二、控制流补充
12.1 while-else 与 for-else
Python 中循环可以与 else 结合使用,当循环正常结束(没有被 break 打断)时执行 else 块:
python
# while-else
count = 0
while count < 5:
print(count, end=" ")
count += 1
else:
print("\nLoop completed normally")
# 输出: 0 1 2 3 4
# Loop completed normally
# for-else:查找质数
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(f"{n} = {x} * {n//x}")
break
else:
print(f"{n} is a prime number")
12.2 pass 语句
pass 是空语句(类似 C 中的单个分号),不做任何事,常用作占位符:
python
def to_be_implemented():
pass # TODO: 待实现
class EmptyClass:
pass
十三、Python 的动态特性
Python 是动态解析变量的语言,在运行时解析类型。这意味着:
python
# 变量不需要预先声明类型
x = 10 # x 是 int
x = "hello" # x 变成 string(完全合法)
x = [1, 2, 3] # x 变成 list
# isinstance() 和 type() 的区别
class A: pass
class B(A): pass
b = B()
print(isinstance(b, B)) # True
print(isinstance(b, A)) # True(考虑继承关系)
print(type(b) == B) # True
print(type(b) == A) # False(不考虑继承)
总结
Python 以其简洁优雅的语法和强大的标准库,成为当今最流行的编程语言之一。本文涵盖了以下核心知识点:
- 环境管理: pyenv 版本管理、pip 镜像配置
- Python 2/3 差异: print 语法、整数除法、字符串编码等关键区别
- 基础语法: 缩进规则、变量与常量、数据类型、运算符
- 五种标准数据类型: Numbers、String、List、Tuple、Dictionary,以及 Set
- 函数编程: 默认参数、可变参数、lambda 表达式
- 列表推导式: 简洁高效的列表创建方式
- 迭代器与生成器: yield 关键字和惰性求值
- 面向对象: 类、继承、私有成员、魔术方法
- 异常处理: try-except-finally 和 raise
- 常用标准库: re、time、os 等模块
Python 的设计哲学是"简单优于复杂"、"优雅优于丑陋"。掌握这些基础后,你可以进一步学习 Python 在数据分析、Web 开发、自动化运维、机器学习等领域的应用。
原始笔记来源:
yisiderui/study on python.pyzyh/LearnPython.py