PYTHON学习导图与实例代码100条
以下是Python 学习导图
涵盖从基础到进阶 的核心知识点,帮助你系统化学习 Python:
Python 学习路线
1 Python 基础语法
1.1变量与数据类型
- 数字(`int`, `float`, `complex`)
- 字符串(`str`)及常用方法(`split()`, `join()`, `format()`)
- 布尔值(`bool`)
- 空值(`None`)
1.2运算符
- 算术运算符(`+`, `-`, `*`, `/`, `%`, ``)
- 比较运算符(`==`, `!=`, `>`, `<`)
- 逻辑运算符(`and`, `or`, `not`)
- 赋值运算符(`=`, `+=`, `-=`)
1.3输入与输出
- `input()` 获取用户输入
- `print()` 格式化输出(`f-string`, `.format()`)
1.4注释
- 单行注释 `#`
- 多行注释 `'''` 或 `"""`
2 流程控制
2.1条件语句
- `if` / `elif` / `else`
- 三元运算符 `x if condition else y`
2.2循环结构
- `while` 循环
- `for` 循环(`range()`、遍历列表/字典)
- `break` / `continue` / `pass`
3 数据结构
3.1列表(List)
- 增删改查(`append()`, `remove()`, `pop()`, `slice`)
- 列表推导式 `[x for x in range(10)]`
3.2元组(Tuple)
- 不可变序列
- 解包 `a, b = (1, 2)`
3.3字典(Dict)
- `{key: value}` 结构
- `keys()`, `values()`, `items()`
3.4集合(Set)
- 去重 `{1, 2, 3}`
- 集合运算(`&`, `|`, `-`)
4 函数与模块
4.1函数定义
- `def func():`
- 参数(位置参数、默认参数、可变参数 `*args`, `kwargs`)
- 返回值 `return`
- 匿名函数 `lambda x: x + 1`
4.2模块与包
- `import math` / `from math import sqrt`
- 自定义模块
- `__name__ == "__main__"` 的作用
5 文件操作
5.1文件读写
- `open()` + `read()` / `write()`
- `with` 语句(自动关闭文件)
5.2常见文件格式
- `.txt`(文本文件)
- `.csv`(`csv` 模块)
- `.json`(`json.load()` / `json.dump()`)
6 面向对象编程(OOP)
6.1类与对象
- `class MyClass:`
- `__init__` 构造方法
- 实例属性 vs 类属性
6.2继承与多态
- `class Child(Parent):`
- 方法重写 `override`
-魔术方法
- `__str__`, `__len__`, `__add__`
7 异常处理
7.1 `try` / `except` / `finally`
7.2 常见异常类型:
- `ValueError`, `TypeError`, `IndexError`, `KeyError`
7.3 自定义异常 `raise Exception("Error")`
8 常用内置库
- `math`(数学计算)
- `random`(随机数)
- `datetime`(日期时间)
- `os`(操作系统交互)
- `sys`(系统参数)
- `re`(正则表达式)
9 Python 进阶
9.1迭代器与生成器
- `iter()` / `next()`
- `yield` 生成器
9.2装饰器
- `@decorator`
9.3多线程与多进程
- `threading` / `multiprocessing`
9.4网络编程
- `socket` / `requests`(HTTP 请求)
10 实战项目方向
-Web 开发(Django / Flask)
-数据分析(Pandas / NumPy)
-爬虫(Scrapy / BeautifulSoup)
-自动化脚本(文件处理 / 定时任务)
-机器学习(Scikit-learn / TensorFlow)
学习建议
1.先学基础语法 →再练小项目(如计算器、猜数字游戏)。
2.理解 OOP →尝试写更复杂的程序(如学生管理系统)。
3.掌握常用库 →进入专业方向(如数据分析、Web 开发)。
4.多写代码 +多看优秀开源项目(GitHub)。
推荐资源
-书籍:《Python Crash Course》、《流畅的 Python》
-网站:
- 官方文档 [docs.python.org](
https://docs.python.org/3/)
- 菜鸟教程 [runoob.com](
https://www.runoob.com/python3/)
- LeetCode(刷算法题)
按照这个导图一步步学习,你可以从零基础 到Python 高手!下面是所有主题的实例,希望对所有初学者有所帮助!
1. Python 基础语法
1.1 变量与数据类型
-- 数字(`int`, `float`, `complex`)
python
# 整数
a = 10
print(type(a)) # <class 'int'>
# 浮点数
b = 20.5
print(type(b)) # <class 'float'>
# 复数
c = 3 + 4j
print(type(c)) # <class 'complex'>
-- 字符串(`str`)及常用方法(`split()`, `join()`, `format()`)
```python
# 字符串
s = "hello world"
print(s.split()) # ['hello', 'world']
# join
words = ['hello', 'world']
print(' '.join(words)) # hello world
# format
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
```
-- 布尔值(`bool`)
python
# 布尔值
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False
print(bool("hello")) # True
-- 空值(`None`)
python
# 空值
x = None
print(x is None) # True
1.2 运算符
-- 算术运算符(`+`, `-`, `*`, `/`, `%`, `**`)
python
# 算术运算符
print(10 + 5) # 15
print(10 - 5) # 5
print(10 * 5) # 50
print(10 / 5) # 2.0
print(10 % 3) # 1
print(10 ** 2) # 100
-- 比较运算符(`==`, `!=`, `>`, `<`)
python
# 比较运算符
print(10 == 5) # False
print(10 != 5) # True
print(10 > 5) # True
print(10 < 5) # False
-- 逻辑运算符(`and`, `or`, `not`)
python
# 逻辑运算符
print(10 > 5 and 20 > 10) # True
print(10 > 5 or 20 < 10) # True
print(not 10 > 5) # False
-- 赋值运算符(`=`, `+=`, `-=`)
python
# 赋值运算符
x = 10
x += 5 # x = x + 5
print(x) # 15
x -= 3 # x = x - 3
print(x) # 12
1.3 输入与输出
-- `input()` 获取用户输入
python
# input
name = input("Enter your name: ")
print("Hello, " + name)
-- `print()` 格式化输出(`f-string`, `.format()`)
python
# f-string
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
# format
print("My name is {} and I am {} years old.".format(name, age))
1.4 注释
-- 单行注释 `#`
python
# 这是单行注释
print("Hello, world!")
-- 多行注释" `'''` 或 `"""`**"
python
"""
这是多行注释
可以写多行内容
"""
print("Hello, world!")
2. 流程控制
2.1 条件语句
-- `if` / `elif` / `else`
python
# if-elif-else
age = 20
if age < 18:
print("You are a minor.")
elif age >= 18 and age < 65:
print("You are an adult.")
else:
print("You are a senior.")
-- 三元运算符 `x if condition else y`
python
# 三元运算符
age = 20
message = "You are an adult." if age >= 18 else "You are a minor."
print(message)
2.2 循环结构
-- `while` 循环
python
# while 循环
count = 0
while count < 5:
print(count)
count += 1
-- `for` 循环(`range()`、遍历列表/字典)
python
# for 循环
for i in range(5):
print(i)
# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 遍历字典
person = {"name": "Alice", "age": 25}
for key, value in person.items():
print(f"{key}: {value}")
-- `break` / `continue` / `pass`
python
# break
for i in range(10):
if i == 5:
break
print(i)
# continue
for i in range(10):
if i % 2 == 0:
continue
print(i)
# pass
for i in range(10):
pass
3. 数据结构
3.1 列表(List)
-- 增删改查(`append()`, `remove()`, `pop()`, `slice`)
python
# 列表操作
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # 添加元素
print(fruits) # ['apple', 'banana', 'cherry', 'orange']
fruits.remove("banana") # 删除元素
print(fruits) # ['apple', 'cherry', 'orange']
fruits.pop() # 删除最后一个元素
print(fruits) # ['apple', 'cherry']
# 切片
print(fruits[1:2]) # ['cherry']
-- 列表推导式 `[x for x in range(10)]`
python
# 列表推导式
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
3.2 元组(Tuple)
-- 不可变序列
python
# 元组
point = (1, 2)
print(point[0]) # 1
-- 解包 `a, b = (1, 2)`
python
# 解包
a, b = (1, 2)
print(a) # 1
print(b) # 2
3.3 字典(Dict)
-- `{key: value}` 结构
python
# 字典
person = {"name": "Alice", "age": 25}
print(person["name"]) # Alice
-- `keys()`, `values()`, `items()`
python
# 字典方法
print(person.keys()) # dict_keys(['name', 'age'])
print(person.values()) # dict_values(['Alice', 25])
print(person.items()) # dict_items([('name', 'Alice'), ('age', 25)])
3.4 集合(Set)
-- 去重 `{1, 2, 3}`
python
# 集合
numbers = {1, 2, 2, 3}
print(numbers) # {1, 2, 3}
-- 集合运算(`&`, `|`, `-`)
python
# 集合运算
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1 & set2) # {2, 3}
print(set1 | set2) # {1, 2, 3, 4}
print(set1 - set2) # {1}
4. 函数与模块
4.1 函数定义
-- `def func():`
python
# 定义函数
def greet(name):
print(f"Hello, {name}")
4.2 函数参数
-- 参数(位置参数、默认参数、可变参数 `*args`, `**kwargs`)
python
# 位置参数
def add(a, b):
return a + b
print(add(3, 4)) # 7
# 默认参数
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob", "Hi") # Hi, Bob!
# 可变参数 *args
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4)) # 10
# 可变参数 **kwargs
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25)
-- 返回值 `return`
python
# 返回值
def multiply(a, b):
return a * b
result = multiply(3, 4)
print(result) # 12
-- 匿名函数`lambda x: x + 1`
python
# 匿名函数
add_one = lambda x: x + 1
print(add_one(5)) # 6
4.2 模块与包
-- `import math` / `from math import sqrt`
python
# 导入模块
import math
print(math.sqrt(16)) # 4.0
# 从模块导入特定函数
from math import sqrt
print(sqrt(16)) # 4.0
-- 自定义模块
python
# 创建一个自定义模块 mymodule.py
# mymodule.py
def greet(name):
print(f"Hello, {name}!")
# 使用自定义模块
# main.py
import mymodule
mymodule.greet("Alice")
-- `__name__ == "__main__"` 的作用
python
# mymodule.py
def greet(name):
print(f"Hello, {name}!")
if __name__ == "__main__":
greet("Alice")
# 运行 mymodule.py 时会打印 "Hello, Alice!"
# 但当作为模块导入时,不会自动执行 greet("Alice")
5. 文件操作
5.1 文件读写
-- `open()` + `read()` / `write()`
python
# 写入文件
with open("example.txt", "w") as file:
file.write("Hello, world!")
# 读取文件
with open("example.txt", "r") as file:
content = file.read()
print(content) # Hello, world!
-- `with` 语句(自动关闭文件)
python
# 使用 with 语句自动关闭文件
with open("example.txt", "r") as file:
content = file.read()
print(content) # Hello, world!
5.2 常见文件格式
-- `.txt`(文本文件)
python
# 读取和写入文本文件
with open("example.txt", "w") as file:
file.write("This is a text file.")
with open("example.txt", "r") as file:
print(file.read()) # This is a text file.
-- `.csv`(`csv` 模块)
python
# 写入 CSV 文件
import csv
with open("example.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 25])
writer.writerow(["Bob", 30])
# 读取 CSV 文件
with open("example.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
-- `.json`(`json.load()` / `json.dump()`)
python
# 写入 JSON 文件
import json
data = {"name": "Alice", "age": 25}
with open("example.json", "w") as file:
json.dump(data, file)
# 读取 JSON 文件
with open("example.json", "r") as file:
data = json.load(file)
print(data) # {'name': 'Alice', 'age': 25}
6. 面向对象编程(OOP)
6.1 类与对象
-- `class MyClass:`
python
# 定义类
class MyClass:
def __init__(self, value):
self.value = value
def show(self):
print(f"Value: {self.value}")
# 创建对象
obj = MyClass(10)
obj.show() # Value: 10
-- `__init__` 构造方法
python
# 构造方法
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# 创建对象
person = Person("Alice", 25)
person.greet() # Hello, my name is Alice and I am 25 years old.
-- 实例属性 vs 类属性
python
# 实例属性和类属性
class MyClass:
class_attribute = "I am a class attribute"
def __init__(self, value):
self.instance_attribute = value
# 访问类属性
print(MyClass.class_attribute) # I am a class attribute
# 创建对象并访问实例属性
obj = MyClass(10)
print(obj.instance_attribute) # 10
6.2 继承与多态
-- `class Child(Parent):`
python
# 继承
class Animal:
def speak(self):
return "Animal speaks"
class Dog(Animal):
def speak(self):
return "Dog barks"
# 创建对象
animal = Animal()
dog = Dog()
print(animal.speak()) # Animal speaks
print(dog.speak()) # Dog barks
-- 方法重写 `override`
python
# 方法重写
class Parent:
def show(self):
print("Parent show")
class Child(Parent):
def show(self):
print("Child show")
# 创建对象
child = Child()
child.show() # Child show
6.3 魔术方法
-- `__str__`, `__len__`, `__add__`
python
# 魔术方法
class MyClass:
def __init__(self, value):
self.value = value
def __str__(self):
return f"MyClass({self.value})"
def __len__(self):
return len(self.value)
def __add__(self, other):
return MyClass(self.value + other.value)
# 创建对象
obj1 = MyClass("Hello")
obj2 = MyClass("World")
print(obj1) # MyClass(Hello)
print(len(obj1)) # 5
print(obj1 + obj2) # MyClass(HelloWorld)
7. 异常处理
7.1 `try` / `except` / `finally`
python
# 异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This will always execute")
7.2 常见异常类型
python
# 常见异常类型
try:
print(10 / 0) # ZeroDivisionError
except ZeroDivisionError as e:
print(e)
try:
print(int("abc")) # ValueError
except ValueError as e:
print(e)
try:
print([1, 2, 3][4]) # IndexError
except IndexError as e:
print(e)
try:
print({"a": 1}["b"]) # KeyError
except KeyError as e:
print(e)
7.3 自定义异常 `raise Exception("Error")`
python
# 自定义异常
class MyException(Exception):
pass
try:
raise MyException("Something went wrong")
except MyException as e:
print(e)
8. 常用内置库
8.1 `math`(数学计算)
python
# math 模块
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.sin(math.pi / 2)) # 1.0
print(math.cos(math.pi)) # -1.0
print(math.factorial(5)) # 120
8.2 `random`(随机数)
python
# random 模块
import random
print(random.random()) # 生成一个0到1之间的随机浮点数
print(random.randint(1, 10)) # 生成一个1到10之间的随机整数
print(random.choice([1, 2, 3, 4, 5])) # 随机选择列表中的一个元素
8.3 `datetime`(日期时间)
python
# datetime 模块
from datetime import datetime, timedelta
now = datetime.now()
print(now) # 当前日期和时间
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 格式化日期时间
tomorrow = now + timedelta(days=1)
print(tomorrow) # 明天的日期和时间
8.4 `os`(操作系统交互)
python
# os 模块
import os
print(os.getcwd()) # 获取当前工作目录
os.mkdir("test_dir") # 创建一个目录
print(os.listdir()) # 列出当前目录下的文件和目录
os.rmdir("test_dir") # 删除一个目录
8.5 `sys`(系统参数)
python
# sys 模块
import sys
print(sys.argv) # 获取命令行参数
print(sys.path) # 获取Python模块搜索路径
8.6 `re`(正则表达式)
python
# re 模块
import re
text = "Hello, my email is example@example.com"
pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"
match = re.search(pattern, text)
if match:
print("Found email:", match.group())
9. Python 进阶
9.1 迭代器与生成器
-- `iter()` / `next()`
```python
# 迭代器
my_list = [1, 2, 3]
my_iter = iter(my_list)
print(next(my_iter)) # 1
print(next(my_iter)) # 2
print(next(my_iter)) # 3
```
-- `yield` 生成器
```python
# 生成器
def my_generator():
yield 1
yield 2
yield 3
gen = my_generator()
for value in gen:
print(value) # 1, 2, 3
9.2 装饰器
python
# 装饰器
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
9.3 多线程与多进程
-- `threading`
python
# 多线程
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
```
-- `multiprocessing`
python
# 多进程
import multiprocessing
def print_numbers():
for i in range(5):
print(i)
process = multiprocessing.Process(target=print_numbers)
process.start()
process.join()
9.4 网络编程
-- `socket`
python
# socket 示例(服务器端)
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(1)
print("Server is listening...")
client_socket, addr = server_socket.accept()
print("Connection from", addr)
data = client_socket.recv(1024)
print("Received:", data.decode())
client_socket.sendall("Hello from server".encode())
client_socket.close()
server_socket.close()
-- `requests`(HTTP 请求)
python
# requests 示例
import requests
response = requests.get("https://jsonplaceholder.typicode.com/todos/1")
print(response.json())
10. 其他示例
10.1 文件操作(续)
-- 读取文件的每一行
python
# 逐行读取文件
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # 去掉行尾的换行符
10.2 数据结构(续)
-- 列表排序
```python
# 列表排序
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
-- 字典排序
python
# 字典排序
my_dict = {"a": 3, "b": 1, "c": 2}
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_dict) # {'b': 1, 'c': 2, 'a': 3}
```
10.3 函数与模块(续)
-- 闭包
python
# 闭包
def outer_function(x):
def inner_function(y):
return x + y
return inner_function
closure = outer_function(10)
print(closure(5)) # 15
10.4 异常处理(续)
-- 自定义异常类
python
# 自定义异常类
class MyCustomError(Exception):
def __init__(self, message):
super().__init__(message)
try:
raise MyCustomError("This is a custom error")
except MyCustomError as e:
print(e)
10.5 面向对象编程(续)
-- 类方法和静态方法
python
# 类方法和静态方法
class MyClass:
class_var = "I am a class variable"
def __init__(self, value):
self.instance_var = value
@classmethod
def class_method(cls):
print(cls.class_var)
@staticmethod
def static_method():
print("I am a static method")
MyClass.class_method() # I am a class variable
MyClass.static_method() # I am a static method