Python知识超级汇总|Python Super Summary of Knowledge
Python作为一门功能强大且应用广泛的编程语言,其知识体系涵盖了从基础语法到高级特性,再到丰富的库和框架。通过掌握这些知识,开发者可以在多个领域进行高效的编程工作,如数据分析、Web开发、人工智能等。希望本汇总能够帮助读者全面深入地理解和掌握Python编程,为实际项目开发打下坚实的基础。在学习过程中,建议读者多进行实践,通过实际项目来加深对知识的理解和运用。
温馨提示:下方的英语标注可能会有一些问题,如果大家看的懂中文建议尽量看中文版的
Kind reminder: There may be some issues with the English annotations below. If you understand Chinese, it is recommended to read the Chinese version as much as possible
Python知识超级汇总
文章目录
一、引言
Python 是一种高级、解释型、通用的编程语言,以其简洁、易读、易维护的代码风格和强大的功能而受到广泛欢迎。它拥有丰富的库和框架,可应用于多个领域,如 Web 开发、数据科学、人工智能、自动化脚本、游戏开发等。本汇总将全面介绍 Python 的基础知识、高级特性以及常用的库和框架,帮助读者全面掌握 Python 编程。
二、Python 基础
(一)安装与环境配置
- 下载安装包:从 Python 官方网站https://www.python.org/downloads/下载适合自己操作系统的 Python 安装包。
- 安装过程:运行安装包,按照提示进行安装。在安装过程中,建议勾选“Add Python to PATH”选项,以便在命令行中直接使用 Python 命令。
- 环境变量检查:安装完成后,打开命令行,输入“python --version”,如果显示 Python 的版本号,则说明安装成功。
(二)基本语法
- 注释
- 单行注释:使用“#”符号,例如:
# 这是一个单行注释
- 多行注释:使用三个单引号(‘’')或三个双引号(“”"),例如:
''' 这是一个 多行注释 ''' """ 这也是一个 多行注释 """
- 变量与数据类型
- 变量命名规则:变量名由字母、数字和下划线组成,不能以数字开头,且区分大小写。例如:
my_variable = 10
。 - 常见数据类型:
- 整数(int):表示整数,如
10
、-5
。 - 浮点数(float):表示小数,如
3.14
、-2.5
。 - 字符串(str):用单引号或双引号括起来的文本,如
'Hello, World!'
、"Python is great"
。 - 布尔值(bool):只有两个值
True
和False
。 - 空值(None):表示空对象。
- 整数(int):表示整数,如
- 变量命名规则:变量名由字母、数字和下划线组成,不能以数字开头,且区分大小写。例如:
- 运算符
- 算术运算符:
+
(加)、-
(减)、*
(乘)、/
(除)、%
(取模)、**
(幂运算)、//
(整除)。例如:
result = 5 + 3 # 加法,结果为8 result = 10 / 3 # 除法,结果为3.3333333333333335 result = 10 % 3 # 取模,结果为1 result = 2 ** 3 # 幂运算,结果为8 result = 10 // 3 # 整除,结果为3
- 比较运算符:
==
(等于)、!=
(不等于)、>
(大于)、<
(小于)、>=
(大于等于)、<=
(小于等于)。例如:
is_equal = 5 == 3 # 比较是否相等,结果为False is_greater = 5 > 3 # 比较大小,结果为True
- 逻辑运算符:
and
(与)、or
(或)、not
(非)。例如:
result = (5 > 3) and (2 < 4) # 逻辑与,结果为True result = (5 > 3) or (2 > 4) # 逻辑或,结果为True result = not (5 > 3) # 逻辑非,结果为False
- 赋值运算符:
=
(赋值)、+=
(加等于)、-=
(减等于)、*=
(乘等于)、/=
(除等于)、%=
(取模等于)、**=
(幂等于)、//=
(整除等于)。例如:
num = 5 num += 3 # 相当于num = num + 3,结果num为8
- 算术运算符:
(三)流程控制
- 条件语句(if - elif - else)
age = 18
if age < 18:
print("未成年人")
elif age == 18:
print("刚成年")
else:
print("成年人")
- 循环语句
- for 循环:用于遍历可迭代对象(如列表、字符串、元组等)。
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
- while 循环:只要条件为真,就会一直循环执行。
count = 0
while count < 5:
print(count)
count += 1
- 循环控制语句
- 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)
(四)数据结构
- 列表(list)
- 是一种有序的可变序列,可以包含不同类型的元素。
- 创建列表:
my_list = [1, 2, 3, 'apple', 3.14]
- 访问列表元素:通过索引访问,索引从 0 开始。
my_list = [1, 2, 3, 'apple', 3.14]
print(my_list[0]) # 输出1
print(my_list[3]) # 输出'apple'
- 修改列表元素:
my_list = [1, 2, 3, 'apple', 3.14]
my_list[0] = 10
print(my_list) # 输出[10, 2, 3, 'apple', 3.14]
- 列表常用方法:
append()
:在列表末尾添加一个元素。
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # 输出[1, 2, 3, 4]
- `extend()`:将一个可迭代对象的元素添加到列表中。
my_list = [1, 2, 3]
new_list = [4, 5]
my_list.extend(new_list)
print(my_list) # 输出[1, 2, 3, 4, 5]
- `insert()`:在指定位置插入一个元素。
my_list = [1, 2, 3]
my_list.insert(1, 1.5)
print(my_list) # 输出[1, 1.5, 2, 3]
- `remove()`:移除列表中第一个匹配的元素。
my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # 输出[1, 3, 2]
- `pop()`:移除并返回指定位置的元素,默认移除最后一个元素。
my_list = [1, 2, 3]
element = my_list.pop(1)
print(element) # 输出2
print(my_list) # 输出[1, 3]
- 元组(tuple)
- 是一种有序的不可变序列,通常用于存储一组相关的数据。
- 创建元组:
my_tuple = (1, 2, 3, 'apple')
# 也可以省略括号
my_tuple = 1, 2, 3, 'apple'
- 访问元组元素:与列表类似,通过索引访问。
my_tuple = (1, 2, 3, 'apple')
print(my_tuple[0]) # 输出1
print(my_tuple[3]) # 输出'apple'
- 集合(set)
- 是一种无序的、不重复的数据集合,常用于去重和集合运算。
- 创建集合:
my_set = {1, 2, 3, 3} # 自动去重,实际集合为{1, 2, 3}
# 也可以使用set()函数创建
my_set = set([1, 2, 3, 3])
- 集合常用方法:
add()
:添加一个元素。
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # 输出{1, 2, 3, 4}
- `remove()`:移除一个元素,如果元素不存在会报错。
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # 输出{1, 3}
- `discard()`:移除一个元素,如果元素不存在不会报错。
my_set = {1, 2, 3}
my_set.discard(4)
print(my_set) # 输出{1, 2, 3}
- `union()`:返回两个集合的并集。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.union(set2)
print(result) # 输出{1, 2, 3, 4, 5}
- `intersection()`:返回两个集合的交集。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.intersection(set2)
print(result) # 输出{3}
- 字典(dict)
- 是一种无序的键值对集合,用于存储和查找数据。
- 创建字典:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
- 访问字典元素:通过键访问。
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
print(my_dict['name']) # 输出'John'
- 修改字典元素:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
my_dict['age'] = 26
print(my_dict) # 输出{'name': 'John', 'age': 26, 'city': 'New York'}
- 字典常用方法:
keys()
:返回字典的所有键。
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
keys = my_dict.keys()
print(keys) # 输出dict_keys(['name', 'age', 'city'])
- `values()`:返回字典的所有值。
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
values = my_dict.values()
print(values) # 输出dict_values(['John', 25, 'New York'])
- `items()`:返回字典的所有键值对。
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
items = my_dict.items()
print(items) # 输出dict_items([('name', 'John'), ('age', 25), ('city', 'New York')])
- `get()`:通过键获取值,如果键不存在返回默认值(默认为 None)。
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
value = my_dict.get('name')
print(value) # 输出'John'
value = my_dict.get('gender', 'Unknown')
print(value) # 输出'Unknown'
三、Python 高级特性
(一)函数
- 定义函数
def add_numbers(a, b):
return a + b
- 函数参数
- 位置参数:按顺序传递的参数。
def greet(name, message):
print(f"{name}, {message}")
greet('John', 'Hello!')
- 默认参数:在定义函数时为参数设置默认值。
def greet(name, message='Hello!'):
print(f"{name}, {message}")
greet('John')
greet('John', 'How are you?')
- 可变参数(*args):用于接收任意数量的位置参数,以元组形式传递。
def sum_numbers(*args):
result = 0
for num in args:
result += num
return result
print(sum_numbers(1, 2, 3))
print(sum_numbers(1, 2, 3, 4, 5))
- **关键字参数(kwargs):用于接收任意数量的关键字参数,以字典形式传递。
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name='John', age=25, city='New York')
- 匿名函数(lambda 函数)
- 是一种没有名字的小函数,通常用于简单的表达式。
add = lambda a, b: a + b
print(add(3, 5))
(二)迭代器与生成器
- 迭代器
- 是一个可以被迭代(遍历)的对象,实现了
__iter__()
和__next__()
方法。 - 创建迭代器:
- 是一个可以被迭代(遍历)的对象,实现了
my_list = [1, 2, 3]
my_iterator = iter(my_list)
print(next(my_iterator)) # 输出1
print(next(my_iterator)) # 输出2
print(next(my_iterator)) # 输出3
# 当没有更多元素时,会抛出StopIteration异常
# print(next(my_iterator))
- 生成器
- 是一种特殊的迭代器,使用
yield
关键字来生成值,而不是使用return
。 - 生成器函数:
- 是一种特殊的迭代器,使用
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
print(next(fib)) # 输出0
print(next(fib)) # 输出1
print(next(fib)) # 输出1
print(next(fib)) # 输出2
- 生成器表达式:
squares = (i ** 2 for i in range(10))
print(next(squares)) # 输出0
print(next(squares)) # 输出1
print(next(squares)) # 输出4
(三)装饰器
- 定义装饰器
- 是一种特殊的函数,用于修改其他函数的行为,而不修改函数的源代码。
def my_decorator(func):
def wrapper():
print("Before function execution")
func()
print("After function execution")
return wrapper
- 使用装饰器
@my_decorator
def say_hello():
print("Hello!")
say_hello()
(四)面向对象编程(OOP)
- 类的定义
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} is barking!")
- 对象的创建
my_dog = Dog('Buddy', 3)
my_dog.bark()
- 继承
class GoldenRetriever(Dog):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
def fetch(self):
print(f"{self.name} is fetching!")
my_golden = GoldenRetriever('Charlie', 2, 'Golden')
my_golden.bark()
my_golden.fetch()
- 多态
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("Woof!")
class Cat(Animal):
def speak(self):
print("Meow!")
def make_animal_speak(animal):
animal.speak()
dog = Dog()
cat = Cat()
make_animal_speak(dog)
make_animal_speak(cat)
在这里,make_animal_speak
函数接受一个Animal
类型的对象,但是由于Dog
和Cat
类都继承自Animal
并且重写了speak
方法,所以根据传入对象的不同,speak
方法会表现出不同的行为,这就是多态性的体现。
- 封装
- 封装是将数据和操作数据的方法绑定在一起,对外部隐藏内部实现细节。在Python中,通过约定来模拟私有属性和方法。
class BankAccount:
def __init__(self, balance=0):
self._balance = 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 0 < amount <= self._balance:
self._balance -= amount
print(f"Withdrew {amount}. New balance: {self._balance}")
else:
print("Insufficient funds or invalid withdrawal amount.")
account = BankAccount(1000)
account.deposit(500)
account.withdraw(300)
# 虽然可以通过account._balance直接访问,但不建议这样做,破坏了封装性
在这个例子中,_balance
前面的下划线表示它是一个“私有”属性,理论上不应该从类的外部直接访问,而应该通过类提供的deposit
和withdraw
方法来操作它。
- 魔法方法
- 魔法方法是Python中特殊的方法,它们的名字以双下划线开头和结尾,如
__init__
、__str__
等。 __str__
方法用于定义对象的字符串表示形式,当使用print
函数输出对象时会调用这个方法。
- 魔法方法是Python中特殊的方法,它们的名字以双下划线开头和结尾,如
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
point = Point(3, 4)
print(point)
__len__
方法用于定义对象的长度,当使用len
函数时会调用这个方法。
class MyList:
def __init__(self):
self.data = []
def append(self, item):
self.data.append(item)
def __len__(self):
return len(self.data)
my_list = MyList()
my_list.append(1)
my_list.append(2)
print(len(my_list))
(五)异常处理
- 捕获异常
- 使用
try - except
语句来捕获和处理异常。
- 使用
try:
result = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed.")
- 捕获多个异常
try:
my_list = [1, 2, 3]
print(my_list[5])
result = 10 / 0
except IndexError:
print("Index out of range.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
else
和finally
子句else
子句在try
块中没有发生异常时执行。finally
子句无论是否发生异常都会执行。
try:
num = int("10")
except ValueError:
print("Invalid number conversion.")
else:
print(f"Converted number: {num}")
finally:
print("This will always be printed.")
(六)模块与包
- 模块
- 模块是一个包含Python定义和语句的文件,扩展名为
.py
。通过导入模块,可以使用其中定义的函数、类和变量。 - 创建一个
my_module.py
文件:
- 模块是一个包含Python定义和语句的文件,扩展名为
# my_module.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
- 在另一个文件中导入并使用这个模块:
import my_module
result = my_module.add(3, 5)
print(result)
result = my_module.multiply(4, 6)
print(result)
- 也可以使用
from...import
语句导入模块中的特定内容:
from my_module import add, multiply
result = add(3, 5)
print(result)
result = multiply(4, 6)
print(result)
- 包
- 包是一个包含多个模块的目录,目录下必须有一个
__init__.py
文件(在Python 3.3+中,这个文件可以为空,但它仍然用于标识该目录是一个包)。 - 假设目录结构如下:
- 包是一个包含多个模块的目录,目录下必须有一个
my_package/
__init__.py
module1.py
module2.py
- 在
module1.py
中定义一些内容:
# module1.py
def greet():
print("Hello from module1!")
- 在
module2.py
中定义一些内容:
# module2.py
def farewell():
print("Goodbye from module2!")
- 在其他文件中导入包中的模块:
import my_package.module1
import my_package.module2
my_package.module1.greet()
my_package.module2.farewell()
- 也可以使用
from...import
语句:
from my_package.module1 import greet
from my_package.module2 import farewell
greet()
farewell()
四、Python 常用库与框架
(一)NumPy
- 数组创建
- NumPy 是Python的核心科学计算支持库,提供了快速、灵活、明确的数组对象。
import numpy as np
# 创建一维数组
arr1d = np.array([1, 2, 3, 4, 5])
print(arr1d)
# 创建二维数组
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2d)
# 创建全零数组
zeros_arr = np.zeros((3, 4))
print(zeros_arr)
# 创建全一数组
ones_arr = np.ones((2, 3))
print(ones_arr)
# 创建指定范围的数组
range_arr = np.arange(1, 10, 2)
print(range_arr)
- 数组操作
- 索引和切片:与Python列表类似,但更强大。
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(arr[3])
print(arr[2:7])
print(arr[::2])
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr2d[1, 2])
print(arr2d[0:2, 1:])
- 数学运算:对数组中的元素进行各种数学运算。
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
add_result = arr1 + arr2
print(add_result)
multiply_result = arr1 * arr2
print(multiply_result)
square_result = np.square(arr1)
print(square_result)
sum_result = np.sum(arr1)
print(sum_result)
(二)pandas
- 数据读取与写入
- pandas 是用于数据处理和分析的库,提供了快速、灵活、明确的数据结构。
import pandas as pd
# 读取CSV文件
data = pd.read_csv('data.csv')
print(data.head())
# 写入CSV文件
data.to_csv('new_data.csv', index=False)
- 数据选择与过滤
import pandas as pd
data = pd.read_csv('data.csv')
# 选择列
column_data = data['column_name']
print(column_data)
# 选择行
row_data = data.iloc[0]
print(row_data)
# 过滤数据
filtered_data = data[data['age'] > 20]
print(filtered_data)
- 数据清理与预处理
- 处理缺失值:
import pandas as pd
data = pd.read_csv('data_with_missing.csv')
# 删除含有缺失值的行
cleaned_data = data.dropna()
print(cleaned_data)
# 使用指定值填充缺失值
data.fillna(0, inplace=True)
print(data)
- 处理重复值:
import pandas as pd
data = pd.read_csv('data_with_duplicates.csv')
# 删除重复行
unique_data = data.drop_duplicates()
print(unique_data)
(三)Matplotlib
- 基本绘图
- Matplotlib 是Python的绘图库,用于创建静态、动态和交互式可视化。
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Sine Wave')
plt.show()
- 多子图绘制
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)
plt.subplot(2, 1, 1)
plt.plot(x, y1)
plt.title('Sine Wave')
plt.subplot(2, 1, 2)
plt.plot(x, y2)
plt.title('Cosine Wave')
plt.tight_layout()
plt.show()
(四)Flask
- 基本应用创建
- Flask 是一个轻量级的Web应用框架,用于快速开发Web应用。
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
- 路由与视图函数
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'This is the index page.'
@app.route('/about')
def about():
return 'This is the about page.'
if __name__ == '__main__':
app.run()
(五)Django
- 项目创建与基本配置
- Django 是一个功能强大的Web应用框架,具有丰富的插件和工具。
- 使用命令行创建Django项目:
django - admin startproject myproject
- 配置
settings.py
文件,如数据库配置、静态文件路径等。
- 创建模型与数据库操作
- 在
models.py
文件中定义模型类:
- 在
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publication_date = models.DateField()
- 使用命令行迁移数据库:
python manage.py makemigrations
python manage.py migrate
- 创建视图与URL配置
- 在
views.py
文件中定义视图函数:
- 在
from django.http import HttpResponse
from.models import Book
def book_list(request):
books = Book.objects.all()
response = ""
for book in books:
response += f"{book.title} by {book.author} - {book.publication_date}<br>"
return HttpResponse(response)
- 在
urls.py
文件中配置URL:
from django.contrib import admin
from django.urls import path
from. import views
urlpatterns = [
path('admin/', admin.site.urls),
path('books/', views.book_list, name='book_list'),
]
五、总结
Python 作为一门功能强大且应用广泛的编程语言,其知识体系涵盖了从基础语法到高级特性,再到丰富的库和框架。通过掌握这些知识,开发者可以在多个领域进行高效的编程工作,如数据分析、Web 开发、人工智能等。希望本汇总能够帮助读者全面深入地理解和掌握 Python 编程,为实际项目开发打下坚实的基础。在学习过程中,建议读者多进行实践,通过实际项目来加深对知识的理解和运用。
Python Super Summary of Knowledge
文章目录
I. Introduction
Python is a high-level, interpreted, and general-purpose programming language that is widely popular for its concise, easy-to-read, easy-to-maintain code style and powerful features. It has a rich set of libraries and frameworks that can be applied to several fields such as web development, data science, artificial intelligence, automation scripting, game development, and more. This summary will provide a comprehensive introduction to the basics, advanced features, and commonly used libraries and frameworks of Python to help readers fully grasp Python programming.
Second, Python Basics
(1) Installation and environment configuration
- Download the installation package: Download the Python installation package suitable for your operating system from the official Python website [https://www.python.org/downloads/] (https://www.python.org/downloads/).
- Installation process: Run the installation package and follow the prompts to install. During the installation process, it is recommended to check the “Add Python to PATH” option so that you can use Python commands directly from the command line.
- Environment Variable Check: After the installation is complete, open the command line, enter “python --version”, if the version number of Python is displayed, it means that the installation is successful.
(2) Basic grammar
- Notes
- Single-line comments: Use the “#” symbol, for example:
# This is a one-line note
- Multi-line comments: Use three single quotes (‘’') or three double quotes (“”"), for example:
''' Here's one Multi-line comments ''' """ This is also one Multi-line comments """
- Variables & Data Types
- Variable naming convention: Variable names are composed of letters, numbers, and underscores, cannot start with numbers, and are case-sensitive. For example: ‘my_variable = 10’.
- Common data types:
- Integer (int): indicates an integer, such as ‘10’ and ‘-5’.
- Float: Represents a decimal number, such as ‘3.14’, ‘-2.5’.
- 字符串(str):用单引号或双引号括起来的文本,如
'Hello, World!'
、"Python is great"
。 - Bool: There are only two values, ‘True’ and ‘False’.
- 空值(None):表示空对象。
- Operator
- Arithmetic operators: ‘+’ (add), ‘-’ (subtract), ‘*’ (multiply), ‘/’ (divide), ‘%’ (modulo), ‘**’ (power operation), ‘//’ (divisible). For example:
result = 5 + 3 # addition, the result is 8 result = 10 / 3 # division, the result is 3.333333333333333335 result = 10 % 3 # modulo, the result is 1 result = 2 ** 3 # power operation, the result is 8 result = 10 // 3 # divisible, the result is 3
- Comparison operators: ‘==’ (equals), ‘!=’ (not equal), ‘>’ (greater than), ‘<’ (less than), ‘>=’ (greater than or equal to), ‘<=’ (less than or equal to). For example:
is_equal = 5 == 3 # Compare whether it is equal or not, the result is False is_greater = 5 > 3 # Compare the size and the result is True
- Logical operators: ‘and’, ‘or’, ‘not’. For example:
result = (5 > 3) and (2 < 4) # 逻辑与,结果为True result = (5 > 3) or (2 > 4) # 逻辑或,结果为True result = not (5 > 3) # 逻辑非,结果为False
- Assignment operators: ‘=’ (assignment), ‘+=’ (plus equals), ‘-=’ (minus equals), ‘*=’ (multiplication equals), ‘/=’ (division equals), ‘%=’ (modulo equals), ‘**=’ (power equals), ‘//=’ (divisible equals). For example:
Num = 5 num += 3 #相当于num = num + 3,结果num为8
(3) Process control
- 条件语句(if - elif - else)
age = 18
if age < 18:
print("未成年人")
elif age == 18:
print("just coming-of-age")
else:
print("adult")
- Loop Statement
- For loops: Used to iterate through iterable objects (such as lists, strings, tuples, etc.).
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
- While loop: As long as the condition is true, the loop will always be executed.
count = 0
while count < 5:
print(count)
count += 1
- Loop Control Statement
- Break: Used to terminate the loop immediately.
for i in range(10):
if i == 5:
break
print(i)
- Continue: Skips the remainder of the current loop and continues to the next one.
for i in range(10):
if i % 2 == 0:
continue
print(i)
(4) Data structure
- 列表(list)
- is an ordered variable sequence that can contain different types of elements.
- Create List:
my_list = [1, 2, 3, 'apple', 3.14]
- Access List Element: Access via index, which starts at 0.
my_list = [1, 2, 3, 'apple', 3.14]
print(my_list[0]) # 输出1
print(my_list[3]) # 输出'apple'
- Modify List Element:
my_list = [1, 2, 3, 'apple', 3.14]
my_list[0] = 10
print(my_list) # 输出[10, 2, 3, 'apple', 3.14]
- List Common Methods:
- ‘append()’: Adds an element to the end of the list.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # 输出[1, 2, 3, 4]
- extend(): Adds an iterable object's element to the list.
my_list = [1, 2, 3]
new_list = [4, 5]
my_list.extend(new_list)
print(my_list) # 输出[1, 2, 3, 4, 5]
- 'insert()': Inserts an element at the specified location.
my_list = [1, 2, 3]
my_list.insert(1, 1.5)
print(my_list) # 输出[1, 1.5, 2, 3]
- 'remove()': Removes the first matching element from the list.
my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # 输出[1, 3, 2]
- 'pop()': Removes and returns the element at the specified position, and removes the last element by default.
my_list = [1, 2, 3]
element = my_list.pop(1)
print(element) # 输出2
print(my_list) # 输出[1, 3]
- 元组 (tuple)
- is an ordered, immutable sequence that is typically used to store a set of related data.
- Create tuple:
my_tuple = (1, 2, 3, 'apple')
# Parentheses can also be omitted
my_tuple = 1, 2, 3, 'apple'
- Access tuple elements: Similar to lists, accessed via an index.
my_tuple = (1, 2, 3, 'apple')
print(my_tuple[0]) # 输出1
print(my_tuple[3]) # 输出'apple'
- 集合(set)
- is an unordered, distinct collection of data, commonly used for deduplication and collection operations.
- Create Collection:
my_set = {1, 2, 3, 3} # Auto-deduplication, the actual set is {1, 2, 3}
# It can also be created using the set() function
my_set = set([1, 2, 3, 3])
- Common Methods for Collection:
- ‘add()’: Add an element.
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # 输出{1, 2, 3, 4}
- 'remove()': Removes an element, if the element does not exist, it will report an error.
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # 输出{1, 3}
- 'discard()': removes an element, and does not report an error if the element does not exist.
my_set = {1, 2, 3}
my_set.discard(4)
print(my_set) # 输出{1, 2, 3}
- 'union()': Returns the union of two sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.union(set2)
print(result) # 输出{1, 2, 3, 4, 5}
- `intersection()`:返回两个集合的交集。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.intersection(set2)
print(result) # 输出{3}
- 字典(dict)
- is an unordered collection of key-value pairs that is used to store and find data.
- Create a dictionary:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
- Access to dictionary elements: Access by key.
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
print(my_dict['name']) # 输出'John'
- Modify Dictionary Elements:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
my_dict['age'] = 26
print(my_dict) # 输出{'name': 'John', 'age': 26, 'city': 'New York'}
- Dictionary Common Methods:
- keys(): Returns all keys in the dictionary.
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
keys = my_dict.keys()
print(keys) # 输出dict_keys(['name', 'age', 'city'])
- `values()`:返回字典的所有值。
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
values = my_dict.values()
print(values) # 输出dict_values(['John', 25, 'New York'])
- 'items()': Returns all key-value pairs for the dictionary.
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
items = my_dict.items()
print(items) # 输出dict_items([('name', 'John'), ('age', 25), ('city', 'New York')])
- 'get()': Gets the value by the key, and returns the default value (Never by default) if the key does not exist.
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
value = my_dict.get('name')
print(value) # 输出'John'
value = my_dict.get('gender', 'Unknown')
print(value) # 输出'Unknown'
3. Advanced features of Python
(a) Functions
- Define Functions
def add_numbers(a, b):
return a + b
- Function Parameters
- Positional Parameters: Parameters that are passed sequentially.
def greet(name, message):
print(f"{name}, {message}")
greet('John', 'Hello!')
- Default Parameters: Set default values for parameters when defining functions.
def greet(name, message='Hello!'):
print(f"{name}, {message}")
greet('John')
greet('John', 'How are you?')
- Variadic Parameters (args): Used to receive any number of positional parameters, passed as tuples.
def sum_numbers(*args):
result = 0
for num in args:
result += num
return result
print(sum_numbers(1, 2, 3))
print(sum_numbers(1, 2, 3, 4, 5))
- Keyword Parameters (kwargs): Used to receive any number of keyword parameters, passed in dictionary form.
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name='John', age=25, city='New York')
- 匿名函(lambda 函数)
- is a small function with no name, usually used for simple expressions.
add = lambda a, b: a + b
print(add(3, 5))
(2) Iterators and generators
- Iterator
- is an object that can be iterated over (traversed) and implements the iter()’ and ‘next()’ methods.
- Create an iterator:
my_list = [1, 2, 3]
my_iterator = iter(my_list)
print(next(my_iterator)) # 输出1
print(next(my_iterator)) # 输出2
print(next(my_iterator)) # 输出3
# When there are no more elements, a StopItration exception is thrown
# print(next(my_iterator))
- Generator
- is a special kind of iterator that uses the ‘yield’ keyword to generate values instead of ‘return’.
- Generator Functions:
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
print(next(fib)) # 输出0
print(next(fib)) # 输出1
print(next(fib)) # 输出1
print(next(fib)) # 输出2
- Generator Expressions:
squares = (i ** 2 for i in range(10))
print(next(squares)) # 输出0
print(next(squares)) # 输出1
print(next(squares)) # 输出4
© Decorators
- Defining Decorators
- is a special type of function that modifies the behavior of other functions without modifying the source code of the function.
def my_decorator(func):
def wrapper():
print("Before function execution")
func()
print("After function execution")
return wrapper
- Use Decorators
@my_decorator
def say_hello():
print("Hello!")
say_hello()
(4) Object-Oriented Programming (OOP)
- Definition of Class
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} is barking!")
- Object Creation
my_dog = Dog('Buddy', 3)
my_dog.bark()
- Inheritance
class GoldenRetriever(Dog):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
def fetch(self):
print(f"{self.name} is fetching!")
my_golden = GoldenRetriever('Charlie', 2, 'Golden')
my_golden.bark()
my_golden.fetch()
- Polymorphism
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("Woof!")
class Cat(Animal):
def speak(self):
print("Meow!")
def make_animal_speak(animal):
animal.speak()
dog = Dog()
cat = Cat()
make_animal_speak(dog)
make_animal_speak(cat)
Here, the make_animal_speak function accepts an object of type Animal, but since both the Dog and Cat classes inherit from Animal and override the speak method, the speak method behaves differently depending on the object being passed in, which is a manifestation of polymorphism.
- Encapsulation
- Encapsulation is the way to bind data and manipulate data together, hiding the internal implementation details from the outside. In Python, private properties and methods are emulated by conventions.
class BankAccount:
def __init__(self, balance=0):
self._balance = 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 0 < amount <= self._balance:
self._balance -= amount
print(f"Withdrew {amount}. New balance: {self._balance}")
else:
print("Insufficient funds or invalid withdrawal amount.")
account = BankAccount(1000)
account.deposit(500)
account.withdraw(300)
# Although it can be accessed directly through the account._balance, it is not recommended and breaks the encapsulation
In this example, the underscore before ‘_balance’ indicates that it is a ‘private’ property that should theoretically not be accessed directly from outside the class, but should be manipulated via the ‘deposit’ and ‘withdraw’ methods provided by the class.
- Magic Method
- Magic methods are special methods in Python where their names start and end with a double underscore, e.g. ‘init’, ‘str’, etc.
- The str method is used to define the string representation of the object, and is called when the object is output using the print function.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
point = Point(3, 4)
print(point)
- The ‘len’ method is used to define the length of the object, and is called when using the ‘len’ function.
class MyList:
def __init__(self):
self.data = []
def append(self, item):
self.data.append(item)
def __len__(self):
return len(self.data)
my_list = MyList()
my_list.append(1)
my_list.append(2)
print(len(my_list))
(5) Exception handling
- Catch Exception
- Use the ‘try - except’ statement to catch and handle exceptions.
try:
result = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed.")
- Catch Multiple Exceptions
try:
my_list = [1, 2, 3]
print(my_list[5])
result = 10 / 0
except IndexError:
print("Index out of range.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
- 'else’和’finally’子句
- The ‘else’ clause is executed when no exception occurs in the ‘try’ block.
- The ‘finally’ clause is executed regardless of whether an exception occurs or not.
try:
num = int("10")
except ValueError:
print("Invalid number conversion.")
else:
print(f"Converted number: {num}")
finally:
print("This will always be printed.")
(6) Modules and packages
- Module
- A module is a file containing Python definitions and statements with the extension ‘.py’. By importing a module, you can use the functions, classes, and variables defined in it.
- Create a ‘my_module.py’ file:
# my_module.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
- Import and use this module in another file:
import my_module
result = my_module.add(3, 5)
print(result)
result = my_module.multiply(4, 6)
print(result)
- You can also use ‘from… import’ statement to import something specific in the module:
from my_module import add, multiply
result = add(3, 5)
print(result)
result = multiply(4, 6)
print(result)
- Package
- A package is a directory that contains multiple modules, and there must be a ‘init.py’ file under the directory (in Python 3.3+, this file can be empty, but it is still used to identify the directory as a package).
- Suppose the directory structure looks like this:
my_package/
__init__.py
module1.py
module2.py
- Define something in the ‘module1.py’:
# module1.py
def greet():
print("Hello from module1!")
- Define something in the ‘module2.py’:
# module2.py
def farewell():
print("Goodbye from module2!")
- Import modules from the package in other files:
import my_package.module1
import my_package.module2
my_package.module1.greet()
my_package.module2.farewell()
- You can also use ‘from… import’ statement:
from my_package.module1 import greet
from my_package.module2 import farewell
greet()
farewell()
四、Python 常用库与框架
(a) NumPy
- Array Creation
- NumPy is Python’s core scientific computing support library, providing fast, flexible, and unambiguous array objects.
import numpy as np
# Create a one-dimensional array
arr1d = np.array([1, 2, 3, 4, 5])
print(arr1d)
# Create a 2D array
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2d)
# Create an all-zero array
zeros_arr = np.zeros((3, 4))
print(zeros_arr)
# Create an all-one array
ones_arr = np.ones((2, 3))
print(ones_arr)
# Create an array of specified ranges
range_arr = np.arange(1, 10, 2)
print(range_arr)
- Array Operations
- Indexes and slices: Similar to Python lists, but more powerful.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(arr[3])
print(arr[2:7])
print(arr[::2])
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr2d[1, 2])
print(arr2d[0:2, 1:])
- Math Operations: Perform various math operations on the elements in the array.
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
add_result = arr1 + arr2
print(add_result)
multiply_result = arr1* arr2
print(multiply_result)
square_result = np.square(arr1)
print(square_result)
sum_result = np.sum(arr1)
print(sum_result)
(2) Pandas
- Data Reading and Writing
- pandas is a library for data processing and analysis, providing fast, flexible, and unambiguous data structures.
import pandas as pd
# Read the CSV file
data = pd.read_csv('data.csv')
print(data.head())
# Write to a CSV file
data.to_csv('new_data.csv', index=False)
- Data Selection & Filtering
import pandas as pd
data = pd.read_csv('data.csv')
# Select Columns
column_data = data['column_name']
print(column_data)
# Select Rows
row_data = data.iloc[0]
print(row_data)
# Filter data
filtered_data = data[data['age'] > 20]
print(filtered_data)
- Data Cleansing & Preprocessing
- Handling missing values:
import pandas as pd
data = pd.read_csv('data_with_missing.csv')
# Delete rows with missing values
cleaned_data = data.dropna()
print(cleaned_data)
# Fill in missing values with specified values
data.fillna(0, inplace=True)
print(data)
- Handling duplicate values:
import pandas as pd
data = pd.read_csv('data_with_duplicates.csv')
# Remove duplicate rows
unique_data = data.drop_duplicates()
print(unique_data)
(三)Matplotlib
- Basic Drawing
- Matplotlib is a plotting library for Python for creating static, dynamic, and interactive visualizations.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Sine Wave')
plt.show()
- Multi-subgraph drawing
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)
plt.subplot(2, 1, 1)
plt.plot(x, y1)
plt.title('Sine Wave')
plt.subplot(2, 1, 2)
plt.plot(x, y2)
plt.title('Cosine Wave')
plt.tight_layout()
plt.show()
(四)Flask
- Basic App Creation
- Flask is a lightweight web application framework for rapid web application development.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
- Routing & View Functions
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'This is the index page.'
@app.route('/about')
def about():
return 'This is the about page.'
if __name__ == '__main__':
app.run()
(5) Django
- Project Creation & Basic Configuration
- Django is a powerful web application framework with a rich set of plugins and tools.
- Create a Django project using the command line:
Django - Admin StartProject MyProject
- Configure settings.py files, such as database configurations, static file paths, etc.
- Create Model & Database Operations
- Define the model class in the ‘models.py’ file:
from django.db import models
class Book(models. Model):
title = models. CharField(max_length=100)
author = models. CharField(max_length=100)
publication_date = models. DateField()
- Use the command line to migrate a database:
Python manage.py makemigrations
python manage.py migrate
- Create View & URL Configuration
- Define the view function in the ‘views.py’ file:
from django.http import HttpResponse
from.models import Book
def book_list(request):
books = Book.objects.all()
response = ""
for book in books:
response += f"{book.title} by {book.author} - {book.publication_date}<br>"
return HttpResponse(response)
- Configure the URL in the ‘urls.py’ file:
from django.contrib import admin
from django.urls import path
from. import views
urlpatterns = [
path('admin/', admin.site.urls),
path('books/', views.book_list, name='book_list'),
]
V. Summary
Python is a powerful and widely used programming language with a knowledge base that ranges from basic syntax to high-level features to rich libraries and frameworks. With this knowledge, developers can perform efficient programming in multiple areas, such as data analysis, web development, artificial intelligence, and more. We hope that this summary will help readers understand and master Python programming comprehensively and deeply, and lay a solid foundation for real-world project development. In the learning process, it is recommended that readers practice more and deepen their understanding and application of knowledge through practical projects.
更多推荐
所有评论(0)