Seek neuropeptides, Restrain dopamine.
运行系统:macOS Sonoma 14.6.1
Python编译器:PyCharm 2024.1.4 (Community Edition)
Python版本:3.12
往期链接:
1-5
006 as
as 关键字在 Python 中的主要用途是为模块、上下文管理器和异常处理提供别名或赋值。它有助于提升代码的可读性和简洁性。
- 上下文管理器(with 语句)
# 使用 as 来创建上下文管理器,通常用于文件操作或资源管理:
with open('file1.txt') as file1, open('file2.txt') as file2:
content1 = file1.read()
content2 = file2.read()
- 导入模块
# 在导入模块时,as 可以用来给模块起别名
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import pearsonr as pr, spearmanr as sr
- 异常处理
# 在处理异常时,可以使用 as 将异常对象赋值给一个变量,以便在异常处理块中使用:
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"发生错误: {
e}")
# 输出 发生错误: division by zero
007 import
在 Python 中,import 语句用于导入模块或包,使你能够使用其中定义的函数、类和变量。
- 导入整个模块
import math
result = math.sqrt(16)
print(result) # 输出: 4.0
- 导入特定的函数或类
使用 from … import … 语法可以直接导入特定的函数或类,从而避免使用模块名的前缀:
from math import sqrt, pi
result = sqrt(16)
print(result)
最低0.47元/天 解锁文章
1109

被折叠的 条评论
为什么被折叠?



