# 变量和标识符

# 变量

变量是用于存储数据的容器,变量名可以包含字母、数字和下划线,但不能以数字开头。

a = 1
b = 2
c = a + b
print(c)

# 标识符

标识符是用于标识变量、函数、类、模块等的名称。标识符的命名规则如下:

  • 标识符可以包含字母、数字和下划线,但不能以数字开头。
  • 标识符不能包含空格和特殊字符。
  • 标识符区分大小写。
  • 标识符不能是 Python 的关键字。
# 合法的标识符
my_variable = 10
my_variable_2 = 20
my_variable3 = 30
# 非法的标识符
# my-variable = 10 # 包含空格
# 2my_variable = 10 # 以数字开头
# my-variable-2 = 20 # 包含特殊字符
# class = 10 # 是 Python 关键字

# 数据类型

# 整数 (int)

整数是用于表示整数的类型,例如 1、2、3 等。

a = 10
b = -20
c = 0

# 浮点数 (float)

浮点数是用于表示小数的类型,例如 1.0、2.5、3.14 等。

a = 1.0
b = -2.5
c = 0.0

# 字符串 (str)

字符串是用于表示文本的类型,例如 "hello"、"world" 等。

string1 = "hello"
string2 = 'world'

字符串常见操作:

  1. 字符串拼接:使用 + 运算符将两个字符串连接起来。
a = "hello" + "world" # a="helloworld"
  1. 字符串重复:使用 * 运算符将字符串重复指定次数。
a = "hello" * 3 # a="hellohellohello"
  1. 字符串长度:使用 len() 函数获取字符串的长度。
a = "hello" 
print(len(a)) # 输出 5
  1. 字符串切片:使用 [:] 运算符获取字符串的子串。
a = "hello"
print(a[1:3]) # 输出 "el"
  1. 字符串查找:使用 find() 函数查找子串在字符串中的位置。
a = "hello"
print(a.find("l")) # 输出 2
  1. 字符串替换:使用 replace() 函数替换字符串中的子串。
a = "hello"
print(a.replace("l", "x")) # 输出 "hexxo"
  1. 字符串分割:使用 split() 函数将字符串分割成子串列表。
a = "hello world"
print(a.split(" ")) # 输出 ["hello", "world"]
  1. 字符串大小写转换:使用 upper()lower()capitalize()title() 函数进行大小写转换。
  • upper() :将字符串转换为大写。
  • lower() :将字符串转换为小写。
  • capitalize() :将字符串的首字母转换为大写。
  • title() :将字符串的每个单词的首字母转换为大写。
a = "hello"
print(a.upper()) # 输出 "HELLO"
print(a.lower()) # 输出 "hello"
print(a.capitalize()) # 输出 "Hello"
print(a.title()) # 输出 "Hello"
  1. 字符串格式化:使用 % 运算符或 format() 函数进行字符串格式化。
  • % 运算符:使用 % 运算符进行字符串格式化,格式化字符串中的 %s%d 等占位符会被后面的参数替换。
  • format() 函数:使用 format() 函数进行字符串格式化,格式化字符串中的 {} 占位符会被后面的参数替换。
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age)) # 输出 "My name is Alice and I am 25 years old."
print("My name is {} and I am {} years old.".format(name, age)) # 输出 "My name is Alice and I am 25 years old."
  1. 字符串拼接:使用 join() 函数将列表中的字符串拼接成一个字符串。
a = ["hello", "world"]
print(" ".join(a)) # 输出 "hello world"
  1. 字符串判断:使用 startswith()endswith()isalpha()isdigit()isalnum()isspace() 函数判断字符串的属性。
  • startswith() :判断字符串是否以指定子串开头。
  • endswith() :判断字符串是否以指定子串结尾。
  • isalpha() :判断字符串是否只包含字母。
  • isdigit() :判断字符串是否只包含数字。
  • isalnum() :判断字符串是否只包含字母和数字。
  • isspace() :判断字符串是否只包含空白字符。
a = "hello"
print(a.startswith("h")) # 输出 True
print(a.endswith("o")) # 输出 True
print(a.isalpha()) # 输出 True
print(a.isdigit()) # 输出 False
print(a.isalnum()) # 输出 True
print(a.isspace()) # 输出 False

# 列表 (list)

列表是用于存储多个元素的有序集合,可以包含不同类型的元素。

a = [1, 2, 3, 4, 5]
b = ["hello", "world"]
c = [1, "hello", 3.14]

初始化:

# 空列表
empty_list = []
empty_list = list()
# 初始化带元素的列表
numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'orange']
mixed = [1, 'two', 3.0, [4, 5]]
# 使用列表推导式
squares = [x**2 for x in range(10)]  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
even_numbers = [x for x in range(20) if x % 2 == 0]
# 使用构造函数
from_iterable = list('hello')  # ['h', 'e', 'l', 'l', 'o']
from_range = list(range(5))     # [0, 1, 2, 3, 4]

列表常见操作:

  1. 访问列表元素:使用索引访问列表中的元素。
a = [1, 2, 3, 4, 5]
print(a[0]) # 输出 1
print(a[2]) # 输出 3
  1. 修改列表元素:使用索引修改列表中的元素。
a = [1, 2, 3, 4, 5]
a[0] = 10
print(a) # 输出 [10, 2, 3, 4, 5]
  1. 删除列表元素:使用 del 语句删除列表中的元素。
a = [1, 2, 3, 4, 5]
del a[0]
print(a) # 输出 [2, 3, 4, 5]
  1. 列表切片:使用 [:] 运算符获取列表的子列表。
a = [1, 2, 3, 4, 5]
print(a[1:3]) # 输出 [2, 3]
  1. 列表长度:使用 len() 函数获取列表的长度。
a = [1, 2, 3, 4, 5]
print(len(a)) # 输出 5
  1. 列表追加:使用 append() 方法将元素追加到列表末尾。
a = [1, 2, 3, 4, 5]
a.append(6)
print(a) # 输出 [1, 2, 3, 4, 5, 6]
  1. 列表插入:使用 insert() 方法将元素插入到列表指定位置。
a = [1, 2, 3, 4, 5]
a.insert(1, 10)
print(a) # 输出 [1, 10, 2, 3, 4, 5]
  1. 列表删除:使用 remove() 方法删除列表中指定值的第一个元素。
a = [1, 2, 3, 4, 5]
a.remove(3)
print(a) # 输出 [1, 2, 4, 5]
  1. 列表排序:使用 sort() 方法对列表进行排序。
a = [5, 3, 1, 4, 2]
a.sort()
print(a) # 输出 [1, 2, 3, 4, 5]
  1. 列表反转:使用 reverse() 方法将列表中的元素反转。
a = [1, 2, 3, 4, 5]
a.reverse()
print(a) # 输出 [5, 4, 3, 2, 1]
  1. 列表合并:使用 + 运算符将两个列表合并成一个列表。
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c) # 输出 [1, 2, 3, 4, 5, 6]
  1. 列表复制:使用 copy() 方法复制列表。
a = [1, 2, 3]
b = a.copy()
print(b) # 输出 [1, 2, 3]
  1. 查找列表中元素:使用 in 运算符判断元素是否在列表中。
fruits = ['apple', 'banana', 'orange', 'grape']
# 1. 检查元素是否存在
print('apple' in fruits)  # True
print('watermelon' in fruits)  # False
# 2. 使用 not in 检查不存在
if 'kiwi' not in fruits:
    print("Kiwi is not in the list")  # 会执行
# 3. 使用 count () 方法
# 统计元素出现次数
count = fruits.count('banana')
print(count > 0)  # True
  1. 添加元素的方法
# 1. 追加元素到末尾:append ()
fruits = ["apple", "banana"]
fruits.append("orange")  # 在末尾添加单个元素
print(fruits)  # ['apple', 'banana', 'orange']
# 2. 插入元素到指定位置:insert ()
fruits = ["apple", "banana"]
fruits.insert(1, "mango")  # 在索引 1 位置插入元素
print(fruits)  # ['apple', 'mango', 'banana']
# 3. 添加多个元素:extend ()
fruits = ["apple", "banana"]
fruits.extend(["orange", "grape"])  # 在末尾添加多个元素
print(fruits)  # ['apple', 'banana', 'orange', 'grape']
# 4. 使用 + 运算符连接列表
fruits = ["apple", "banana"]
more_fruits = fruits + ["kiwi", "pear"]  # 创建新列表
print(more_fruits)  # ['apple', 'banana', 'kiwi', 'pear']
# 5. 使用 += 运算符原地扩展
fruits = ["apple", "banana"]
fruits += ["kiwi", "pear"]  # 原地添加多个元素
print(fruits)  # ['apple', 'banana', 'kiwi', 'pear']
# 6. 列表推导式(添加特定元素)
numbers = [1, 2, 3]
doubled_numbers = [x * 2 for x in numbers]  # 创建新列表
print(doubled_numbers)  # [2, 4, 6]

# 元组 (tuple)

元组是用于存储多个元素的有序集合,与列表类似,但元组是不可变的、有序的集合,用圆括号 () 表示。

a = (1, 2, 3, 4, 5)
b = ("hello", "world")
c = (1, "hello", 3.14)

初始化

# 空元组
empty_tuple = ()
empty_tuple = tuple()
# 初始化带元素的元组
coordinates = (10, 20)
colors = ('red', 'green', 'blue')
mixed = (1, 'two', 3.0, [4, 5])
# 单元素元组(需要逗号)
single_element = (42,)  # 注意逗号,否则会被认为是整数 42
not_a_tuple = (42)      # 这不是元组,是整数
# 使用构造函数
from_list = tuple([1, 2, 3])  # (1, 2, 3)
from_string = tuple('abc')    # ('a', 'b', 'c')

元组常见操作:

  1. 访问元组元素:使用索引访问元组中的元素。
a = (1, 2, 3, 4, 5)
print(a[0]) # 输出 1
print(a[2]) # 输出 3
  1. 列表切片:使用 [:] 运算符获取元组的子元组。
a = (1, 2, 3, 4, 5)
print(a[1:3]) # 输出 (2, 3)
  1. 元组长度:使用 len() 函数获取元组的长度。
a = (1, 2, 3, 4, 5)
print(len(a)) # 输出 5
  1. 元组解包:使用 = 运算符将元组中的元素赋值给多个变量。
a = (1, 2, 3)
x, y, z = a
print(x) # 输出 1
print(y) # 输出 2
print(z) # 输出 3
  1. 查找元组中元素:使用 in 运算符判断元素是否在元组中。
# 1. 使用 in 关键字
colors = ('red', 'green', 'blue', 'yellow')
print('red' in colors)  # True
print('purple' in colors)  # False
# 2. 使用 count () 方法
if colors.count('blue') > 0:
    print("Blue is in the tuple")
# 3. 使用 index () 方法
try:
    position = colors.index('green')
    print(f"Green found at position {position}")
except ValueError:
    print("Green not found")
  1. 添加元素的方法

元组不可变,不能直接添加元素,但可以创建新元组。

original = (1, 2, 3)
# 通过连接操作添加元素
new_tuple = original + (4,)  # 注意:单个元素需要加逗号
print(new_tuple)  # 输出: (1, 2, 3, 4)
# 通过解包再创建
another = (*original, 5, 6)
print(another)  # 输出: (1, 2, 3, 5, 6)

# 字典 (dict)

字典是用于存储键值对的集合,键值对之间用冒号分隔,键值对之间用逗号分隔,字典用花括号 {} 表示。

a = {"name": "Alice", "age": 25, "city": "New York"}
b = {1: "one", 2: "two", 3: "three"}

初始化:

# 空字典
empty_dict = {}
empty_dict = dict()
# 初始化带键值对的字典
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
squares = {1: 1, 2: 4, 3: 9, 4: 16}
# 使用字典推导式
squares = {x: x**2 for x in range(5)}  # {0:0, 1:1, 2:4, 3:9, 4:16}
word_counts = {word: len(word) for word in ['apple', 'banana', 'cherry']}
# 使用构造函数
from_list = dict([('name', 'Bob'), ('age', 25), ('city', 'Paris')])
from_keys = dict.fromkeys(['a', 'b', 'c'], 0)  # {'a':0, 'b':0, 'c':0}
# 使用关键字参数
person = dict(name='Charlie', age=35, city='London')

字典常见操作:

  1. 访问字典元素:使用键访问字典中的值。
a = {"name": "Alice", "age": 25, "city": "New York"}
print(a["name"]) # 输出 "Alice"
print(a["age"]) # 输出 25
print(a["city"]) # 输出 "New York"
  1. 修改字典元素:使用键修改字典中的值。
a = {"name": "Alice", "age": 25, "city": "New York"}
a["age"] = 26
print(a) # 输出 {"name": "Alice", "age": 26, "city": "New York"}
  1. 删除字典元素:使用 del 语句删除字典中的键值对。
a = {"name": "Alice", "age": 25, "city": "New York"}
del a["age"]
print(a) # 输出 {"name": "Alice", "city": "New York"}
  1. 字典长度:使用 len() 函数获取字典的长度。
a = {"name": "Alice", "age": 25, "city": "New York"}
print(len(a)) # 输出 3
  1. 字典遍历:使用 for 循环遍历字典中的键值对。
a = {"name": "Alice", "age": 25, "city": "New York"}
for key, value in a.items():
    print(key, value)
  1. 查找字典中元素:使用 in 运算符判断键是否在字典中。
# 1. 检查键是否存在(最常用)
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
# 检查键是否存在
print('name' in person)  # True
print('email' in person)  # False
# 2. 检查值是否存在
print('New York' in person.values())  # True
print('London' in person.values())  # False
# 3. 检查特定键值对
print(('name', 'Alice') in person.items())  # True
print(('age', 25) in person.items())  # False
  1. 添加元素的方法
# 1. 添加键值对:直接赋值
person = {"name": "Alice", "age": 30}
person["city"] = "New York"  # 添加新键值对
print(person)  # {'name': 'Alice', 'age': 30, 'city': 'New York'}
# 2. 批量添加:update ()
person = {"name": "Alice"}
person.update({"age": 30, "city": "Paris"})  # 添加多个键值对
print(person)  # {'name': 'Alice', 'age': 30, 'city': 'Paris'}
# 3. 设置默认值:setdefault ()
person = {"name": "Alice"}
# 添加新键(如果不存在)并设置默认值
age = person.setdefault("age", 25)  
print(person)  # {'name': 'Alice', 'age': 25}
# 4. 字典推导式(添加新元素)
squares = {x: x*x for x in range(1, 6)}  # 创建新字典
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# 集合 (set)

集合是用于存储多个元素的集合,元素不重复且无序。

a = {1, 2, 3, 4, 5}
b = {"hello", "world"}
c = {1, "hello", 3.14}

集合常见操作:

  1. 添加元素:使用 add() 方法向集合中添加元素。
a = {1, 2, 3, 4, 5}
a.add(6)
print(a) # 输出 {1, 2, 3, 4, 5, 6}
  1. 删除元素:使用 remove() 方法从集合中删除指定元素。
a = {1, 2, 3, 4, 5}
a.remove(3)
print(a) # 输出 {1, 2, 4, 5}
  1. 集合长度:使用 len() 函数获取集合的长度。
a = {1, 2, 3, 4, 5}
print(len(a)) # 输出 5
  1. 集合遍历:使用 for 循环遍历集合中的元素。
a = {1, 2, 3, 4, 5}
for i in a:
    print(i)
  1. 集合交集:使用 & 运算符计算两个集合的交集。
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
print(a & b) # 输出 {4, 5}
  1. 集合并集:使用 | 运算符计算两个集合的并集。
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
print(a | b) # 输出 {1, 2, 3, 4, 5, 6, 7, 8}
  1. 集合差集:使用 - 运算符计算两个集合的差集。
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
print(a - b) # 输出 {1, 2, 3}
  1. 集合对称差集:使用 ^ 运算符计算两个集合的对称差集。
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
print(a ^ b) # 输出 {1, 2, 3, 6, 7, 8}

# 布尔值

布尔值是用于表示真假的类型,只有两个值:True 和 False。

a = True
b = False

# 运算符

# 算术运算符

算术运算符用于执行基本的数学运算,例如加法、减法、乘法、除法等。

a = 10
b = 20
c = a + b # c=30
d = a - b # d=-10
e = a * b # e=200
f = a / b # f=0.5
g = a % b # g=10

# 比较运算符

比较运算符用于比较两个值的大小关系,例如大于、小于、等于、不等于等。

a = 10
b = 20
c = a > b  # c=False
d = a < b  # d=True
e = a == b # e=False
f = a != b # f=True

# 逻辑运算符

逻辑运算符用于执行逻辑运算,例如与、或、非等。

a = True
b = False
c = a and b # c=False
d = a or b  # d=True
e = not a   # e=False

# 赋值运算符

赋值运算符用于将一个值赋给一个变量,例如等于、加等于、减等于等。

a = 10
b = 20
a = b # a=20
a += b # a=40
a -= b # a=20
a *= b # a=400
a /= b # a=2.0
a %= b # a=0

# 位运算

符号 功能 规则
& 按位与 两个位都为 1 时,结果为 1
| 按位或 两个位都为 0 时,结果为 0
^ 按位异或 两个位不同时,结果为 1
~ 按位取反 将所有位取反
<< 左移 将所有位向左移动指定的位数
>> 右移 将所有位向右移动指定的位数
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c = a & b # c = 0000 1100 = 12
d = a | b # d = 0011 1101 = 61
e = a ^ b # e = 0011 0001 = 49
f = ~a    # f = 1100 0011 = -61
g = a << 2 # g = 1111 0000 = 240
h = a >> 2 # h = 0000 1111 = 15

# 流程控制

# 条件语句

条件语句用于根据条件执行不同的代码块,例如 if 语句、if-else 语句、if-elif-else 语句等。

a = 10
b = 20
if a > b:
    print("a大于b")
elif a < b:
    print("a小于b")
else:
    print("a等于b")

# 循环语句

循环语句用于重复执行一段代码,例如 for 循环、while 循环等。

  • for 循环:用于遍历一个可迭代对象,例如 列表元组字符串 等。
a = [1, 2, 3, 4, 5]
for i in a:
    print(i)
for i, ceil in enumerate(a):
    print(ceil)
  • while 循环:用于在满足条件时重复执行一段代码。
a = 1
while a < 6:
    print(a)
    a += 1

# 函数

函数是一段可重复使用的代码块,可以接受参数并返回结果。

def add(a, b):
    return a + b
result = add(1, 2)
print(result)

# 函数文档字符串

函数文档字符串用于描述函数的功能和用法,可以使用三引号 """ 包围。

def add(a, b):
    """
    This function adds two numbers.
    
    Parameters:
    a (int): The first number.
    b (int): The second number.
    
    Returns:
    int: The sum of the two numbers.
    """
    return a + b

# 函数参数

函数参数用于传递数据给函数。

  1. 位置参数:按照参数的顺序传递参数。
def add(a, b):
    return a + b
result = add(1, 2)
print(result) # 输出 3
  1. 默认参数:为参数指定默认值。
def add(a, b=2):
    return a + b
result = add(1)
print(result) # 输出 3
  1. 可变参数:使用 * 传递可变数量的参数。
def add(*args):  
# 以元组类型接 args = (1, 2, 3, 4, 5) 
    result = 0
    for i in args:
        result += i
    return result
result = add(1, 2, 3, 4, 5)
print(result) # 输出 15

注意:函数接收可变数量的参数,使用 *args 接收参数, args 是一个元组类型 ()

  1. 关键字参数:通过 ** 传递关键字参数。
def fund(**kwargs):
# 以字典类型接 kwargs = {"name": "Alice", "age": 25, "city": "New York"}
    for key, value in kwargs.items():
        print(key, value)
fund(name="Alice", age=25, city="New York")

注意:函数接收关键字参数,使用 **kwargs 接收参数, kwargs 是一个字典类型 {}

# 函数返回值

函数返回值用于返回函数执行的结果,可以使用 return 语句。

def add(a, b):
    return a + b
result = add(1, 2)
print(result) # 输出 3

# 函数嵌套

  1. 嵌套调用

函数嵌套调用是指在一个函数内部调用另一个函数。

def add(a, b):
    return a + b
def multiply(a, b):
    return a * b
result = multiply(add(1, 2), 3)
print(result) # 输出 9
  1. 嵌套定义
    函数嵌套是指在一个函数内部定义另一个函数。
def outer():
    def inner():
        print("This is inner function")
    inner()
outer()

# 匿名函数

匿名函数是指没有名字的函数,使用 lambda 关键字定义。

格式: 函数名 = lambda 参数列表: 表达式(返回值)

  1. 无参数匿名函数
add = lambda: 1 + 2
print(add()) # 输出 3
  1. 有参数匿名函数
add = lambda a, b: a + b
print(add(1, 2)) # 输出 3
  1. 带默认参数匿名函数
add = lambda a, b=2: a + b
print(add(1)) # 输出 3
  1. 带可变参数匿名函数
add = lambda *args: sum(args)
print(add(1, 2, 3, 4, 5)) # 输出 15
  1. 带关键字参数匿名函数
add = lambda **kwargs: sum(kwargs.values())
print(add(a=1, b=2, c=3)) # 输出 6

# 内置函数

内置函数是指 Python 语言自带的函数,例如 len()max()min() 等。

a = [1, 2, 3, 4, 5]
print(len(a)) # 输出 5
print(max(a)) # 输出 5
print(min(a)) # 输出 1

查看所有内置函数: dir(__builtins__)
dir 函数用于返回一个列表,包含指定对象的所有属性和方法。

import math
print(dir(math))
# 大写的为常量,小写的为函数

# map 函数

map 函数用于将一个函数应用于可迭代对象的每个元素,并返回一个迭代器。

格式: map(函数, 可迭代对象)

a = [1, 2, 3, 4, 5]
result = map(lambda x: x * 2, a) # 将每个元素乘以 2
print(list(result)) # 输出 [2, 4, 6, 8, 10]

# filter 函数

filter 函数用于过滤可迭代对象中的元素,并返回一个迭代器。

格式: filter(函数, 可迭代对象)

a = [1, 2, 3, 4, 5]
result = filter(lambda x: x % 2 == 0, a) # 过滤出偶数
print(list(result)) # 输出 [2, 4]

# reduce 函数

reduce 函数用于将一个函数应用于可迭代对象的每个元素,并返回一个值。
格式: reduce(函数, 可迭代对象)

from functools import reduce
a = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x + y, a) # 将每个元素相加
print(result) # 输出 15

# zip 函数

zip 函数用于将多个可迭代对象中的元素打包成一个个元组,并返回一个迭代器。

格式: zip(可迭代对象1, 可迭代对象2, ...)

a = [1, 2, 3]
b = ['a', 'b', 'c']
result = zip(a, b) # 将每个元素打包成元组
print(list(result)) # 输出 [(1, 'a'), (2, 'b'), (3, 'c')]

# 拆包

对于函数中的多个返回数据,去掉元组,列表或者字典的括号,直接赋值给多个变量。

arr = [1, 2, 3]
a, b, c = arr
print(a) # 输出 1
print(b) # 输出 2
print(c) # 输出 3

# 闭包

闭包是指在一个函数内部定义另一个函数,并且内部函数可以访问外部函数的变量。

def outer():
    x = 10
    def inner():
        print(x)
    return inner
closure = outer()
closure() # 输出 10

# 作用域

作用域是指变量可访问的范围,分为全局作用域和局部作用域。

  1. 全局作用域:在函数外部定义的变量,可以在整个程序中访问。
a = 10
def add(b):
    return a + b
result = add(5)
print(result) # 输出 15
  1. 局部作用域:在函数内部定义的变量,只能在函数内部访问。
def add(a, b):
    c = a + b
    return c
result = add(1, 2)
print(result) # 输出 3
print(c) # 报错,c 未定义

** 注意:** 局部变量 c 只能在 add 函数内部访问,不能在函数外部访问。

局部变量升级为全局变量:使用 global 关键字声明变量为全局变量。

a = 10
def add(b):
    global a
    a = a + b
    return a
result = add(5)
print(result) # 输出 15
print(a) # 输出 15

局部变量 a 升级为全局变量,可以在函数外部访问。

# 异常

异常是指程序运行过程中出现的错误。

异常种类:

异常类型 描述
ZeroDivisionError 除数为 0
TypeError 类型错误
ValueError 值错误
IndexError 索引错误
KeyError 键错误
NameError 名称错误
AttributeError 属性错误
SyntaxError 语法错误
IndentationError 缩进错误
IOError 输入输出错误
EOFError 文件结束错误
ImportError 导入错误
ModuleNotFoundError 模块未找到错误
AssertionError 断言错误
KeyboardInterrupt 键盘中断
SystemExit 系统退出
Exception 所有异常的基类

# 捕获异常。

  • 格式一: try-except
try:
    # 可能出现异常的代码
except 异常类型:
    # 异常处理代码

示例:

try:
    a = 10 / 0
except ZeroDivisionError:
    print("除数不能为0")
  • 格式二: try-except-else
try:
    # 可能出现异常的代码
except 异常类型1:
    # 异常处理代码 1
else:
    # 没有异常时执行的代码
  • 格式三:try-except-finally
try:
    # 可能出现异常的代码
except 异常类型1:
    # 异常处理代码 1
finally:
    # 无论是否出现异常都会执行的代码
  • 格式四:try-except-else-finally
try:
    # 可能出现异常的代码
except 异常类型1:
    # 异常处理代码 1
except 异常类型2:
    # 异常处理代码 2
else:
    # 没有异常时执行的代码
finally:
    # 无论是否出现异常都会执行的代码

# 抛出异常

使用 raise 关键字抛出异常。

格式: raise 异常类型(异常信息)
示例:

def divide(a, b):
    if b == 0:
        raise ZeroDivisionError("除数不能为0")
    return a / b
try:
    result = divide(10, 0)
except ZeroDivisionError as e:
    print(e)

# 模块

模块是包含一组函数、类和变量的文件,可以导入到其他文件中使用。

# 内置模块

Python 内置了一些模块,可以直接使用,例如 mathrandomdatetime 等。

import math
print(math.sqrt(16)) # 输出 4.0

# 第三方模块(第三方库)

第三方模块是指由其他开发者编写的模块,需要先安装才能使用。

安装第三方模块:使用 pip 命令安装。

pip install 模块名

使用第三方模块:使用 import 关键字导入。

import 模块名

使用第三方模块中的函数:使用 模块名.函数名() 调用。

import math
print(math.sqrt(16)) # 输出 4.0

# 自定义模块

自定义模块是指用户自己编写的模块,需要先定义一个 .py 文件,然后在其他文件中导入使用。

注意:自定义模块的文件名不能与 Python 内置模块的文件名相同。

# 导入模块

  1. 导入模块:使用 import 关键字导入。
import 模块名
  1. 使用模块中的函数:使用 模块名.函数名() 调用。
import math
print(math.sqrt(16)) # 输出 4.0
  1. 导入模块中的特定函数:使用 from 模块名 import 函数名 导入。
from math import sqrt
print(sqrt(16)) # 输出 4.0
  1. 导入模块中的所有函数:使用 from 模块名 import * 导入。
from math import *
print(sqrt(16)) # 输出 4.0
  1. 导入模块中的特定变量:使用 from 模块名 import 变量名 导入。
from math import pi
print(pi) # 输出 3.141592653589793

# 起别名

# 模块起别名

使用 as 关键字给模块起别名。

语法: import 模块名 as 别名

import math as m
print(m.sqrt(16)) # 输出 4.0

# 功能起别名

使用 as 关键字给功能起别名。

语法: from 模块名 import 功能 as 别名

from math import sqrt as s
print(s(16)) # 输出 4.0

注意:导入多个功能时,可以使用‘,’隔开,后面功能也可以使用取别名: from math import sqrt as s, pi as p

# 内置全局变量

语法:
if name == “main”:

作用:用来控制 py 文件在不同应用场景下执行不同的逻辑,当模块被直接运行时, __name__ 的值为 "__main__" ,当模块被导入时, __name__ 的值为模块名。
例如:

if __name__ == "__main__":
    print("直接运行")
else:
    print("被导入")

直接运行该文件输出:

直接运行

被导入该文件输出:

被导入

总结:导入不会执行 if __name__ == "__main__": 下的代码,只有直接运行该文件才会执行 if __name__ == "__main__": 下的代码。

#

包是指包含一组模块的文件夹,文件夹中必须包含一个 __init__.py 文件,用于标识该文件夹是一个包。

# init.py

使用包:使用 import 包名.模块名 导入。

import mypackage.mymodule
print(mypackage.mymodule.myfunction())

使用包中的特定模块:使用 from 包名 import 模块名 导入。

from mypackage import mymodule
print(mymodule.myfunction())

使用包中的特定函数:使用 from 包名.模块名 import 函数名 导入。

from mypackage.mymodule import myfunction
print(myfunction())

使用包中的特定变量:使用 from 包名.模块名 import 变量名 导入。

from mypackage.mymodule import myvariable
print(myvariable)

使用包中的所有函数:使用 from 包名.模块名 import * 导入。

from mypackage.mymodule import *
print(myfunction())
print(myvariable)

使用包中的所有变量:使用 from 包名.模块名 import * 导入。

注意:导包会默认执行 __init__.py 文件中的代码。

# all

__all__ 是一个列表,用于指定包中可以被导入的模块。

语法: __all__ = ["模块名1", "模块名2", ...]

示例:

# mypackage/__init__.py
__all__ = ["mymodule1", "mymodule2"]

使用包中的特定模块:使用 from 包名 import 模块名 导入。

from mypackage import mymodule1
print(mymodule1.myfunction())

# 闭包

闭包是指在一个函数内部定义的函数,它可以访问外部函数的局部变量。
实现:

  1. 函数嵌套(内部函数定义在外部函数内部)
  2. 内部函数访问外部函数的局部变量
  3. 外部函数返回内部函数

语法:

def 外部函数():
    变量 =
    def 内部函数():
        print(变量)
    return 内部函数

示例:

def outer_function():
    x = 10
    def inner_function():
        print(x)
    return inner_function # 返回内部函数的引用,即地址
my_function = outer_function()
my_function() # 输出 10

注意:闭包可以访问外部函数的局部变量,但是不能修改外部函数的局部变量。

# 函数引用

函数引用是指将函数赋值给一个变量,然后通过变量调用函数。

语法:

变量 = 函数名
变量()

示例:

def my_function():
    print("Hello, World!")
my_function_ref = my_function
my_function_ref() # 输出 Hello, World!

# 闭包变量

闭包变量是指在闭包中使用的变量,闭包变量实际上只有一份,每次开启内函数都是在使用同一份闭包变量。

def outer_function(n):
    print("outer_function:", n)
    def inner_function(m):
        print("inner_function:",m)
        return n + m
    return inner_function
out = outer_function(10) # outer_function: 10
out(20) # inner_function: 20
print(out(20)) # inner_function: 20 30

# 装饰器

作用:在不修改原有函数代码的情况下,给函数增加新的功能。

  1. 标准装饰器
# 闭包三要素
# 1. 函数嵌套
# 2. 内部函数使用外部函数的变量
# 3. 外部函数返回内部函数的函数名
# 装饰器函数
def send():
    print("发送邮件")
def outer_function(func):
    def inner_function():
        print("before")
        func()
        print("after")
    return inner_function
out = outer_function(send)
out()
  1. 语法糖装饰器
def outer_function(func):
    def inner_function():
        print("before")
        func()
        print("after")
    return inner_function
@outer_function
def send():
    print("发送邮件")
send()
  1. 被装饰的函数有参数
def outer_function(func):
    def inner_function(*args, **kwargs):
        print("before")
        func(*args, **kwargs)
        print("after")
    return inner_function
@outer_function
def send(name):
    print("发送邮件给", name)
send("张三")
  1. 多个装饰器
# 第一个装饰器
def outer_function1(func):
    def inner_function1(*args, **kwargs):
        print("before1")
        func(*args, **kwargs)
        print("after1")
    return inner_function1
# 第二个装饰器
def outer_function2(func):
    def inner_function2(*args, **kwargs):
        print("before2")
        func(*args, **kwargs)
        print("after2")
    return inner_function2
@outer_function1
@outer_function2
# 被装饰的函数
def send(name):
    print("发送邮件给", name)
send("张三")

注意:Python 的装饰器应用顺序是 ​ ​自底向上​​ 的,即靠近 函数定义 的装饰器( @outer_function2 )先被应用,外层装饰器( @outer_function1 )后应用。
以上可以看做: send = outer_function1(outer_function2(send))