Python 从基础到进阶(一套打通)
文章目录
一、Python 入门
1.1 Python 简介
Python 由 Guido van Rossum 于 20 世纪 80 年代末发明,它具有以下显著特点:
print("Hello, World!")
,而在一些其他语言中可能需要更多的代码结构。1.2 安装 Python
Windows
- 访问 Python 官方网站(https://www.python.org/downloads/),根据自己的系统选择合适的 Python 3 版本(通常选择最新的稳定版本)进行下载。
- 运行下载的安装包,在安装过程中,务必勾选 “Add Python to PATH” 选项,这样可以在命令行中直接使用 Python 命令。
- 按照安装向导的提示完成安装。安装完成后,打开命令提示符(CMD),输入
python --version
,如果显示 Python 的版本号,则说明安装成功。
Linux
不同的 Linux 发行版安装 Python 的方式略有不同:
sudo apt-get update
更新软件源,然后输入 sudo apt-get install python3
安装 Python 3。sudo yum install python3
进行安装。安装完成后,同样可以通过 python3 --version
验证安装是否成功。
macOS
macOS 系统自带 Python 2.x,但建议安装 Python 3.x。可以通过以下两种方式安装:
brew install python3
即可完成安装。1.3 第一个 Python 程序
交互式环境
打开命令行工具,输入 python
进入 Python 交互式环境。在交互式环境中,你可以逐行输入 Python 代码并立即看到执行结果。例如:
print("Hello, World!")
按下回车键后,屏幕将显示 Hello, World!
。要退出交互式环境,输入 exit()
或按下 Ctrl + Z
(Windows)/ Ctrl + D
(Linux/macOS)。
脚本文件
使用文本编辑器(如 VS Code、Sublime Text 等)创建一个新文件,将其命名为 hello.py
,并在文件中写入以下代码:
print("Hello, World!")
保存文件后,打开命令行工具,切换到保存 hello.py
文件的目录,输入 python hello.py
并回车,屏幕将显示 Hello, World!
。
二、Python 基础语法
2.1 变量和数据类型
变量
变量是存储数据的容器,在 Python 中,变量使用前不需要声明类型,直接赋值即可。例如:
# 定义一个整数变量
age = 25
# 定义一个字符串变量
name = "John"
变量命名需要遵循以下规则:
if
、else
、for
等)作为变量名。数据类型
数字类型
num1 = 10
。num2 = 3.14
。j
或 J
结尾。例如:num3 = 2 + 3j
。数字类型支持各种算术运算,如加法(+
)、减法(-
)、乘法(*
)、除法(/
)、整除(//
)、取余(%
)和幂运算(**
)。例如:
a = 10
b = 3
print(a + b) # 输出 13
print(a / b) # 输出 3.3333333333333335
print(a // b) # 输出 3
print(a % b) # 输出 1
print(a ** b) # 输出 1000
字符串类型(str)
字符串是用单引号('
)、双引号("
)或三引号('''
或 """
)括起来的文本。例如:
str1 = 'Hello'
str2 = "World"
str3 = '''This is a multi-line
string.'''
字符串支持拼接(+
)、重复(*
)等操作,还可以通过索引和切片来访问字符串中的字符。例如:
str4 = str1 + " " + str2
print(str4) # 输出 "Hello World"
print(str1 * 3) # 输出 "HelloHelloHello"
print(str4[0]) # 输出 "H"
print(str4[0:5]) # 输出 "Hello"
布尔类型(bool)
布尔类型只有两个值:True
和 False
,通常用于条件判断。例如:
is_student = True
is_teacher = False
2.2 运算符
算术运算符
除了前面提到的基本算术运算符,还有一些复合赋值运算符,如 +=
、-=
、*=
、/=
等。例如:
x = 5
x += 3 # 相当于 x = x + 3
print(x) # 输出 8
比较运算符
比较运算符用于比较两个值的大小关系,返回布尔值。常见的比较运算符有 ==
(等于)、!=
(不等于)、>
(大于)、<
(小于)、>=
(大于等于)、<=
(小于等于)。例如:
a = 10
b = 5
print(a > b) # 输出 True
print(a == b) # 输出 False
逻辑运算符
逻辑运算符用于组合多个布尔表达式,常见的逻辑运算符有 and
(逻辑与)、or
(逻辑或)、not
(逻辑非)。例如:
x = 5
y = 10
print(x > 3 and y < 20) # 输出 True
print(x < 3 or y > 20) # 输出 False
print(not (x > 3)) # 输出 False
位运算符
位运算符用于对整数的二进制表示进行操作,常见的位运算符有 &
(按位与)、|
(按位或)、^
(按位异或)、~
(按位取反)、<<
(左移)、>>
(右移)。例如:
a = 5 # 二进制表示为 0101
b = 3 # 二进制表示为 0011
print(a & b) # 按位与,输出 1(二进制 0001)
print(a | b) # 按位或,输出 7(二进制 0111)
2.3 控制流语句
条件语句
条件语句用于根据条件的真假来执行不同的代码块,Python 中的条件语句使用 if-elif-else
结构。例如:
age = 18
if age < 18:
print("未成年人")
elif age == 18:
print("刚成年")
else:
print("成年人")
条件语句可以嵌套使用,以实现更复杂的逻辑。
循环语句
for
循环
for
循环用于遍历序列(如列表、元组、字符串等)中的元素。例如:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
还可以使用 range()
函数生成一个整数序列进行遍历。例如:
for i in range(5):
print(i)
while
循环
while
循环在条件为真时重复执行代码块,直到条件变为假。例如:
i = 0
while i < 5:
print(i)
i += 1
在循环中,可以使用 break
语句提前终止循环,使用 continue
语句跳过当前循环的剩余部分,直接进入下一次循环。例如:
for i in range(10):
if i == 5:
break
print(i)
for i in range(10):
if i % 2 == 0:
continue
print(i)
三、Python 数据结构
3.1 列表(List)
列表是一种可变的有序序列,用方括号 []
表示。列表中的元素可以是不同的数据类型。例如:
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "hello", True]
列表操作
print(numbers[0])
输出 1。numbers[2] = 10
。append()
方法在列表末尾添加一个元素,使用 extend()
方法将一个列表的元素添加到另一个列表的末尾,使用 insert()
方法在指定位置插入一个元素。例如:numbers.append(6)
numbers.extend([7, 8])
numbers.insert(2, 9)
remove()
方法删除指定值的第一个元素,使用 pop()
方法删除指定索引的元素(默认删除最后一个元素),使用 del
语句删除指定索引的元素。例如:numbers.remove(9)
numbers.pop(2)
del numbers[0]
print(numbers[1:3])
输出列表中索引为 1 到 2 的元素。3.2 元组(Tuple)
元组是一种不可变的有序序列,用圆括号 ()
表示。元组一旦创建,其元素不能被修改。例如:
point = (3, 4)
元组的访问方式与列表类似,通过索引来访问元素。例如:print(point[0])
输出 3。
3.3 集合(Set)
集合是一种无序且唯一的数据结构,用花括号 {}
或 set()
函数创建。集合中的元素不能重复。例如:
fruits = {"apple", "banana", "cherry"}
empty_set = set()
集合操作
add()
方法添加一个元素,使用 update()
方法添加多个元素。例如:fruits.add("orange")
fruits.update({"grape", "kiwi"})
remove()
方法删除指定元素,如果元素不存在会抛出异常;使用 discard()
方法删除指定元素,如果元素不存在不会抛出异常。例如:fruits.remove("apple")
fruits.discard("banana")
union()
或 |
)、交集(intersection()
或 &
)、差集(difference()
或 -
)等运算。例如:set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # 输出 {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # 输出 {3}
print(set1.difference(set2)) # 输出 {1, 2}
3.4 字典(Dictionary)
字典是一种无序的键值对集合,用花括号 {}
表示,键和值之间用冒号 :
分隔。字典中的键必须是唯一的,且通常是不可变类型(如字符串、数字、元组)。例如:
person = {"name": "John", "age": 25, "city": "New York"}
字典操作
print(person["name"])
输出 “John”。person["age"] = 26
。person["job"] = "Engineer"
。del
语句删除指定键的元素,使用 pop()
方法删除指定键的元素并返回其值。例如:del person["city"]
job = person.pop("job")
keys()
方法遍历键,使用 values()
方法遍历值,使用 items()
方法遍历键值对。例如:for key in person.keys():
print(key)
for value in person.values():
print(value)
for key, value in person.items():
print(key, value)
四、Python 函数
4.1 定义和调用函数
函数是一段具有特定功能的代码块,可以重复使用。在 Python 中,使用 def
关键字定义函数。例如:
def greet(name):
print(f"Hello, {name}!")
# 调用函数
greet("Alice")
函数可以有返回值,使用 return
语句返回值。例如:
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 输出 8
4.2 函数参数
位置参数
位置参数是最常见的参数类型,按照参数的顺序传递。例如:
def power(x, n):
return x ** n
result = power(2, 3) # 2 的 3 次方
关键字参数
关键字参数通过参数名传递,不需要按照参数的顺序。例如:
result = power(n=3, x=2)
默认参数
在定义函数时,可以为参数提供默认值。如果调用函数时没有传递该参数,则使用默认值。例如:
def power(x, n=2):
return x ** n
print(power(3)) # 使用默认参数,输出 9
print(power(3, 3)) # 传递自定义参数,输出 27
可变参数
\*args
:用于接收任意数量的位置参数,将这些参数封装成一个元组。例如:def sum_numbers(*args):
total = 0
for num in args:
total += num
return total
result = sum_numbers(1, 2, 3, 4)
print(result) # 输出 10
\**kwargs
:用于接收任意数量的关键字参数,将这些参数封装成一个字典。例如:def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="John", age=25, city="New York")
4.3 匿名函数(Lambda 函数)
匿名函数是一种简单的函数,没有函数名,使用 lambda
关键字定义。通常用于简单的、一次性的操作。例如:
square = lambda x: x ** 2
print(square(5)) # 输出 25
4.4 函数的嵌套和闭包
函数的嵌套
在 Python 中,函数可以嵌套定义,即在一个函数内部定义另一个函数。例如:
def outer_function():
def inner_function():
print("This is an inner function.")
inner_function()
outer_function()
闭包
闭包是指有权访问另一个函数作用域中变量的函数。例如:
def outer_function(x):
def inner_function(y):
return x + y
return inner_function
closure = outer_function(10)
result = closure(5)
print(result) # 输出 15
五、Python 面向对象编程
5.1 类和对象
类是对象的抽象模板,对象是类的具体实例。在 Python 中,使用 class
关键字定义类。例如:
class Person:
5.1 类和对象
class Person:
# 类属性,所有实例共享
species = "Homo sapiens"
# 构造方法,在创建对象时自动调用
def __init__(self, name, age):
# 实例属性,每个实例有自己独立的副本
self.name = name
self.age = age
# 实例方法,通过实例调用
def greet(self):
print(f"Hello, my name is {self.name} and I'm {self.age} years old.")
# 类方法,通过类名或实例调用,第一个参数为 cls 表示类本身
@classmethod
def get_species(cls):
return cls.species
# 静态方法,通过类名或实例调用,没有默认的第一个参数
@staticmethod
def is_adult(age):
return age >= 18
# 创建对象
p1 = Person("John", 25)
p2 = Person("Alice", 20)
# 调用实例方法
p1.greet()
# 调用类方法
print(Person.get_species())
# 调用静态方法
print(Person.is_adult(p2.age))
解释
species
是类属性,所有 Person
类的实例都共享这个属性。name
和 age
是实例属性,每个 Person
对象都有自己独立的 name
和 age
值。__init__
:在创建对象时自动调用,用于初始化对象的属性。greet
是实例方法,通过对象实例调用,第一个参数 self
指向调用该方法的对象实例。get_species
是类方法,使用 @classmethod
装饰器,第一个参数 cls
指向类本身,可以通过类名或实例调用。is_adult
是静态方法,使用 @staticmethod
装饰器,没有默认的第一个参数,可以通过类名或实例调用。5.2 继承
继承是面向对象编程的重要特性之一,它允许一个类(子类)继承另一个类(父类)的属性和方法。
# 定义父类
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("Animal speaks")
# 定义子类,继承自 Animal 类
class Dog(Animal):
def speak(self):
print(f"{self.name} barks")
# 定义另一个子类
class Cat(Animal):
def speak(self):
print(f"{self.name} meows")
# 创建对象
dog = Dog("Buddy")
cat = Cat("Whiskers")
# 调用方法
dog.speak()
cat.speak()
解释
Dog
和 Cat
类继承自 Animal
类,它们继承了 Animal
类的 __init__
方法和 name
属性。Dog
和 Cat
类重写了 speak
方法,实现了自己独特的行为,这称为方法的重写(覆盖)。5.3 多态
多态是指不同的对象可以对相同的消息做出不同的响应。在 Python 中,多态通过继承和方法重写来实现。
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("Dog barks")
class Cat(Animal):
def speak(self):
print("Cat meows")
def animal_speak(animal):
animal.speak()
# 创建对象
dog = Dog()
cat = Cat()
# 调用函数
animal_speak(dog)
animal_speak(cat)
解释
animal_speak
函数接受一个 Animal
类型的对象作为参数,无论传入的是 Dog
还是 Cat
对象,都可以调用其 speak
方法,实现了多态。5.4 封装
封装是指将数据和操作数据的方法绑定在一起,并隐藏对象的内部实现细节。在 Python 中,通过访问控制来实现封装。
class BankAccount:
def __init__(self, account_number, balance):
# 私有属性,以双下划线开头
self.__account_number = account_number
self.__balance = balance
# 公有方法,用于获取账户余额
def get_balance(self):
return self.__balance
# 公有方法,用于存款
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"Deposited {amount}. New balance: {self.__balance}")
else:
print("Invalid deposit amount.")
# 公有方法,用于取款
def withdraw(self, amount):
if amount > 0 and amount <= self.__balance:
self.__balance -= amount
print(f"Withdrew {amount}. New balance: {self.__balance}")
else:
print("Invalid withdrawal amount.")
# 创建对象
account = BankAccount("123456", 1000)
# 访问公有方法
print(account.get_balance())
account.deposit(500)
account.withdraw(200)
# 尝试直接访问私有属性(会报错)
# print(account.__balance)
解释
__account_number
和 __balance
是私有属性,以双下划线开头,不能直接从类外部访问。get_balance
、deposit
和 withdraw
是公有方法,通过这些方法可以安全地访问和修改私有属性。六、Python 模块和包
6.1 模块
模块是一个包含 Python 代码的文件,扩展名为 .py
。模块可以包含函数、类、变量等。
自定义模块
创建一个名为 math_utils.py
的文件,内容如下:
# math_utils.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
print("Error: division by zero")
在另一个 Python 文件中使用该模块:
# main.py
import math_utils
result = math_utils.add(3, 5)
print(result)
导入模块的方式
import 模块名
:导入整个模块,使用时需要通过模块名来访问模块中的函数和变量。from 模块名 import 函数名/类名/变量名
:从模块中导入指定的函数、类或变量,使用时不需要通过模块名。from math_utils import add, subtract
result1 = add(3, 5)
result2 = subtract(8, 3)
print(result1)
print(result2)
from 模块名 import \*
:导入模块中的所有内容,使用时不需要通过模块名,但不建议使用,因为可能会导致命名冲突。6.2 包
包是一个包含多个模块的目录,目录下必须有一个 __init__.py
文件(Python 3.3 及以后版本不是必需的,但为了兼容性建议保留)。
创建包
创建一个名为 my_package
的目录,在该目录下创建 __init__.py
文件和两个模块文件 module1.py
和 module2.py
。
my_package/
__init__.py
module1.py
module2.py
module1.py
内容如下:
# module1.py
def func1():
print("This is func1 from module1")
module2.py
内容如下:
# module2.py
def func2():
print("This is func2 from module2")
使用包
在另一个 Python 文件中使用该包:
# main.py
from my_package import module1, module2
module1.func1()
module2.func2()
__init__.py
文件的作用
__init__.py
文件中编写初始化代码,在导入包时自动执行。__all__
变量控制 from 包名 import *
导入的内容。例如,在 __init__.py
中添加以下代码:# __init__.py
from .module1 import func1
from .module2 import func2
__all__ = ['func1', 'func2']
然后在另一个文件中可以使用 from my_package import *
导入 func1
和 func2
。
七、Python 进阶主题
7.1 文件操作
打开和关闭文件
在 Python 中,可以使用 open()
函数打开文件,使用 close()
方法关闭文件。open()
函数的常用模式有:
'r'
:只读模式(默认)。'w'
:写入模式,会覆盖文件原有内容。'a'
:追加模式,在文件末尾添加内容。'b'
:二进制模式,用于处理二进制文件。# 打开文件
file = open("test.txt", "w")
# 写入文件
file.write("Hello, Python!")
# 关闭文件
file.close()
# 打开文件以读取内容
file = open("test.txt", "r")
# 读取文件内容
content = file.read()
print(content)
# 关闭文件
file.close()
使用 with
语句
with
语句可以自动管理文件的打开和关闭,避免手动调用 close()
方法。
with open("test.txt", "r") as file:
content = file.read()
print(content)
文件读取方法
read()
:读取整个文件内容。readline()
:读取一行内容。readlines()
:读取所有行,返回一个列表,每个元素是一行内容。with open("test.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line.strip()) # 去除每行末尾的换行符
7.2 异常处理
在 Python 中,使用 try-except
语句来捕获和处理异常。
try:
num = 10 / 0
except ZeroDivisionError:
print("除数不能为零")
try:
file = open("nonexistent.txt", "r")
except FileNotFoundError:
print("文件未找到")
finally:
# 无论是否发生异常,finally 块中的代码都会执行
if 'file' in locals():
file.close()
异常类型
Python 有许多内置的异常类型,如 ZeroDivisionError
、FileNotFoundError
、TypeError
等。还可以使用 else
子句,当 try
块中没有发生异常时执行。
try:
num = 10 / 2
except ZeroDivisionError:
print("除数不能为零")
else:
print(f"结果: {num}")
自定义异常
可以通过继承 Exception
类来创建自定义异常。
class MyException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
try:
raise MyException("这是一个自定义异常")
except MyException as e:
print(e)
7.3 装饰器
装饰器是一种特殊的函数,它可以接受一个函数作为参数,并返回一个新的函数,用于扩展原函数的功能。
简单装饰器
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
带参数的装饰器
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
类装饰器
class MyDecorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print("Before function call")
result = self.func(*args, **kwargs)
print("After function call")
return result
@MyDecorator
def say_goodbye():
print("Goodbye!")
say_goodbye()
7.4 生成器
生成器是一种特殊的迭代器,它可以在需要时逐个生成值,而不是一次性生成所有值,从而节省内存。
生成器函数
使用 yield
关键字定义生成器函数。
def my_generator():
yield 1
yield 2
yield 3
gen = my_generator()
# 迭代生成器
for num in gen:
print(num)
生成器表达式
生成器表达式类似于列表推导式,但使用圆括号。
gen_expr = (x * 2 for x in range(5))
for num in gen_expr:
print(num)
7.5 并发编程
多线程
Python 中的 threading
模块可以用于实现多线程编程。
import threading
def print_numbers():
for i in range(5):
print(i)
def print_letters():
for letter in 'abcde':
print(letter)
# 创建线程
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
# 启动线程
thread1.start()
thread2.start()
# 等待线程结束
thread1.join()
thread2.join()
多进程
Python 中的 multiprocessing
模块可以用于实现多进程编程。
import multiprocessing
def print_numbers():
for i in range(5):
print(i)
def print_letters():
for letter in 'abcde':
print(letter)
if __name__ == '__main__':
# 创建进程
process1 = multiprocessing.Process(target=print_numbers)
process2 = multiprocessing.Process(target=print_letters)
# 启动进程
process1.start()
process2.start()
# 等待进程结束
process1.join()
process2.join()
异步编程
Python 中的 asyncio
模块可以用于实现异步编程,适用于 I/O 密集型任务。
import asyncio
async def hello():
print("Hello")
await asyncio.sleep(1)
print("World")
async def main():
await asyncio.gather(hello(), hello())
asyncio.run(main())
7.6 正则表达式
正则表达式是一种用于匹配字符串模式的工具,Python 中的 re
模块提供了正则表达式的支持。
import re
# 匹配手机号码
pattern = r'^1[3-9]\d{9}$'
phone_number = '13800138000'
if re.match(pattern, phone_number):
print("是有效的手机号码")
else:
print("不是有效的手机号码")
# 查找所有匹配项
text = "Hello 123 World 456"
numbers = re.findall(r'\d+', text)
print(numbers)
# 替换匹配项
new_text = re.sub(r'\d+', '###', text)
print(new_text)
7.7 数据库操作
Python 可以与多种数据库进行交互,以 SQLite 为例:
import sqlite3
# 连接到数据库
conn = sqlite3.connect('example.db')
# 创建游标对象
cursor = conn.cursor()
# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)''')
# 插入数据
cursor.execute("INSERT INTO users (name, age) VALUES (?,?)", ('John', 25))
# 提交事务
conn.commit()
# 查询数据
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭连接
conn.close()
基础部分补充
#
)和块注释(使用三引号 '''
或 """
)。合理的注释有助于开发者理解代码的逻辑和功能,特别是在团队协作或项目后期维护时非常重要。数据结构部分补充
heapq
模块提供了堆操作的功能,但文档未涉及。堆是一种特殊的树形数据结构,常被用于实现优先队列,在算法设计和优化中应用广泛。queue
模块提供了线程安全的队列实现,包括普通队列(Queue
)、优先队列(PriorityQueue
)和后进先出队列(LifoQueue
),适用于多线程编程场景。函数部分补充
send()
、throw()
和 close()
方法。send()
方法可以向生成器内部发送一个值,并恢复生成器的执行;throw()
方法用于在生成器内部抛出一个异常;close()
方法用于关闭生成器。面向对象编程部分补充
abc
模块提供了抽象基类的功能,用于定义接口和规范子类的行为。通过定义抽象方法,要求子类必须实现这些方法,增强了代码的可维护性和可扩展性。模块和包部分补充
setuptools
或 poetry
等工具创建 Python 包的分发文件(如 .whl
或 .tar.gz
),并将其发布到 PyPI(Python Package Index)上,供其他开发者安装和使用。venv
、virtualenv
或 conda
等工具可以创建独立的 Python 虚拟环境,隔离不同项目的依赖,避免版本冲突。进阶部分补充
socket
模块进行底层网络编程,实现 TCP 和 UDP 套接字通信;使用 requests
库进行 HTTP 请求,用于 Web 数据获取和交互;使用 Flask
或 Django
等 Web 框架搭建 Web 应用。NumPy
进行数值计算,Pandas
进行数据处理和分析,Matplotlib
和 Seaborn
进行数据可视化,Scikit-learn
进行机器学习模型的训练和评估,TensorFlow
或 PyTorch
进行深度学习开发。unittest
、pytest
和 doctest
,用于编写和运行单元测试、集成测试等,确保代码的正确性和稳定性。作者:浪子西科