当前位置: 首页 > news >正文

python学习---dayday6

1、异常

        1、捕获异常

基本语法:

try:

       可能发生错误的代码

except:

       如果出现异常执行的代码

        2、捕获指定异常 

基本语法:

try:

        print(name)

except NameError as e:

        print('name变量名称未定义错误')

        print(e)        # 将异常的内容打印输出在控制台

        1、尝试执行的代码异常类型和要捕获的异常类型不一致,会无法捕获异常

        2、一般try下方只放一行尝试执行的代码

        3、捕获多个异常

基本语法:

try:

       1 / 0

        print(name)

except (NameError, zeroDivisionError)as e:

       print('name变量名称未定义错误')

        4、捕获全部异常

基本语法:

try:

       可能发生错误的代码

except Exception as e:

       如果出现异常执行的代码

        5、异常的else

基本语法:

try:

       可能发生错误的代码

except Exception as e:

       如果出现异常执行的代码

else:

        没有异常执行的代码

        6、异常的finally

基本语法:

try:

       可能发生错误的代码

except Exception as e:

       如果出现异常执行的代码

else:

        没有异常执行的代码

finally:

        不管有没有异常都要执行的代码

        7、异常的传递

def func1():print("func1 begin")num = 1 / 0print("func1 over")def func2():print("func2 begin")func1()print("func2 over")def main():try:func2()except Exception as e:print(f"ERRPR:{e}")main()

        func1出现异常,函数调用,有传递,可以直接对func2函数进行捕获异常

 2、模块

        1、模块的导入

基本语法:

import 模块名

import 模块名1, 模块名2

模块名.功能名()

[from 模块名] import [模块 | 类 | 变量 | 函数 | * ] [as 别名]

常用组合形式:

import 模块名

from 模块名 import 类、变量、方法等

from 模块名 import *

import 模块名 as 别名

from 模块名 import 功能名 as 别名

# 导入time模块中所有的方法,但需要使用模块名去引用
import time
time.sleep(5)# 从time模块,只导入sleep方法
from time import sleep
sleep(5)# 导入time模块中所有的方法
from time import *
sleep(5)# as 别名     ---将time模块的引用换一个引用名
import time as t
t.sleep(5)from time import sleep as sl
sl(5)

2、制作自定义模块

1、test.py调用my_module1.py内的test函数 

my_module1.pydef test(a, b):print(a + b)
test.pyimport my_module1
my_module1.test(1, 2)from my_module1 import test
test(2, 3)

2、导入不同文件下同名的函数方法,会调用执行最下边的函数方法

my_module1.pydef test(a, b):print(a + b)
my_module2.pydef test(a, b):print(a - b)
test.py#不同文件下同函数名,会调用最后的函数
from my_module1 import test
from my_module2 import test
test(1, 2)

3、test.py文件只导入模块,运行也会执行my_module1.py文件内的test方法

my_module1.pydef test(a, b):print(a + b)# 其他文件导入这个函数,也会执行
test(5, 5)
test.pyfrom my_module1 import test

使用main方法,可以避免这个执行结果 

my_module1.pydef test(a, b):print(a + b)# 当前文件执行,__name__内置变量会变成__main__,if会变成true,就会执行
if __name__ == '__main__':test(5, 5)

4、使用_ _all_ _变量

my_module1.py# 针对* 只能导入test_A 这个函数方法
__all__ = ['test_A']def test_A(a, b):print(a + b)def test_B(a, b):print(a - b)
test.pyfrom my_module1 import *
test_A(8, 4)
test_B(5, 1)# 使用__all__变量,针对(导入*),只能导入all指定的函数方法
from my_module1 import *
from my_module1 import test_B
test_A(8, 4)
test_B(5, 1)

3、python包

导入包-方式一:

import 包名.模块名

包名.模块名.目标

 使用python package创建包,会自动生成一个__init__.py的文件

my_module1.pydef info_print1():print("1111111")
my_module2.pydef info_print2():print("222222")
test.py# -------方式1 导入--------
# import my_package.my_module1
# import my_package.my_module2
# my_package.my_module1.info_print1()
# my_package.my_module2.info_print2()# -------方式2 导入--------
# from my_package import my_module1
# from my_package import my_module2
# my_module1.info_print1()
# my_module2.info_print2()# -------方式3 导入--------
# from my_package.my_module1 import info_print1
# from my_package.my_module2 import info_print2
# info_print1()
# info_print2()# -------all变量--------
from my_package import *
my_module1.info_print1()
my_module2.info_print2()
__init__.py__all__ = ['my_module1']

4、案例

1、创建 my_utils 包,创建 str_util.py 和 file_util.py 文件,使用 test.py 调用执行

2、str_util.py 内创建 str_reverse(s) 和 substr(s, x, y) 函数

        1、str_reverse(s) 函数,接收传入字符串,将字符串反转返回

s[::-1]        从第几个到第几个开始,-1从后往前

        2、substr(s, x, y) 函数,按照下标x和y,对字符串进行切片

s[x, y]        从x下标到y小标开始切片(不包含y)

3、file_util.py 内创建 print_file_info(file_name) 和 append_to_file(file_name, data) 函数

        1、print_file_info(file_name) 函数,接收传入文件的路径,打印文件的全部内容

        2、append_to_file(file_name, data) 函数,接受文件路径以及传入的数据,将数据追加写入到文件中

4、使用 test.py 文件,导入调用函数

str_util.py# 字符串相关工具# 接收传入字符串
def str_reverse(s):"""将字符串反转返回:param s: 将被反转的字符串:return: 反转后的字符串"""return s[::-1]def substr(s, x, y):"""按照下标x和y,对字符串进行切片:param s: 即将被切片的字符串:param x: 切片的开始下标:param y: 切片的结束下标:return: 切片完成后的字符串"""return s[x:y]if __name__ == '__main__':print(str_reverse("你好世界"))print(substr("python",1,3))
file_util.py# 文件处理相关工具# 如文件不存在则捕获异常,输出提示信息,通过finally关闭文件对象
def print_file_info(file_name):"""接收传入文件的路径,打印文件的全部内容:param file_name: 即将读取的文件路径:return: None"""f = Nonetry:f = open(file_name, "r", encoding="UTF-8")content = f.read()print("内容如下:")print(content)except Exception as e:print(f"ERROR:{e}")finally:if f:   # 如果变量是None,表示False,如果有内容就是Truef.close()def append_to_file(file_name, data):"""接收文件路径以及传入数据,将数据追加写入到文件中:param file_name: 指定的文件路径:param data: 指定的数据:return: None"""f = open(file_name, "a", encoding="UTF-8")f.write(data)f.write("\n")f.close()if __name__ == '__main__':print_file_info("F:\\test.txt")append_to_file("F:\\test.txt", "你好世界!!!")
test.pyfrom my_utils.str_util import *
from my_utils.file_util import *print(str_reverse("你好世界"))
print(substr("python", 0, 4))append_to_file("F:\\test.txt", "你好世界!!!")
print_file_info("F:\\test.txt")


文章转载自:
http://attractor.hfstrb.cn
http://adela.hfstrb.cn
http://artefact.hfstrb.cn
http://agroboy.hfstrb.cn
http://arpanet.hfstrb.cn
http://bopeep.hfstrb.cn
http://artisanship.hfstrb.cn
http://carboniferous.hfstrb.cn
http://aperitive.hfstrb.cn
http://caliginous.hfstrb.cn
http://balkanize.hfstrb.cn
http://cataplexy.hfstrb.cn
http://calciferous.hfstrb.cn
http://blowpipe.hfstrb.cn
http://bellows.hfstrb.cn
http://beleague.hfstrb.cn
http://brusque.hfstrb.cn
http://amphiaster.hfstrb.cn
http://bok.hfstrb.cn
http://casey.hfstrb.cn
http://advise.hfstrb.cn
http://chapiter.hfstrb.cn
http://centesimal.hfstrb.cn
http://accumulate.hfstrb.cn
http://baiza.hfstrb.cn
http://authoritarianism.hfstrb.cn
http://book.hfstrb.cn
http://anastomosis.hfstrb.cn
http://bedin.hfstrb.cn
http://camas.hfstrb.cn
http://www.dtcms.com/a/281810.html

相关文章:

  • 基于华为欧拉系统安装FileGator文件管理器
  • git本地的操作
  • Java 增强 switch 语句详解:从基础到进阶的全面指南
  • 基于conda包的环境创建、激活、管理与删除
  • 如何卸载SQLServer
  • MybatisPlus由浅入深
  • Neo4j Python 驱动库完整教程(带输入输出示例)
  • Supervisor 使用教程:进程守护的最佳实践指南
  • 06-C语言:第06天笔记
  • 数据分析与AI丨从传感器到智能决策:数据驱动企业发展与 ESG 创新的全链路实践
  • 18.理解 Python 中的切片赋值
  • OpenCV-Python Tutorial : A Candy from Official Main Page(三)
  • Redis原理之持久化
  • 【构建 SHAP 解释器】X:每个样本的特征表(不能含 label,否则解释不纯粹)。
  • 隐私计算四大主流开源框架:从学术研究到工业落地,附PySyft实战Demo
  • 梁的振动特征函数分析2
  • 智驾芯片软件分层测试
  • kdump生成转储文件调试内核崩溃、死机
  • 电涡流位移测量技术深度解密
  • View2 UI聊天框架源码分享 - 支持[图文视频]混排 加入AI 分享一套功能强大的View2 UI聊天框架源码
  • Python初学者笔记第十四期 -- (自定义模块与包)
  • NFS磁盘共享
  • 基础专有术语
  • Model Control Protocol 一种开放的应用层协议,让大模型与工具能够协调配合起来,了解他的定义、定位、组成及实现机制...
  • 手提式干粉灭火器检查工作,如何做到可执行、可追溯、可管理?
  • 移动碰撞法 ——套料排版算法——CAD c#
  • java基础(day08)-面向对象
  • Redis 高频面试题
  • 【删库跑路】一次删除pip的所有第三方库
  • vllm本地部署qwen3-4b