id=int(input("id:")) l=[1,2,3]assertidinrange(len(l)),"索引超出范围!"print(l[id])exceptAssertionError as e:print(e)finally: #不管有没有异常,finally里面的语句都执行print("finally") 3.日志模块(logging) 常用日志级别:info(通知)、debug(调试)、error(错误)、warning(警告)、critical(严重...
方法三:用logging替换print(),和assert比,logging不会抛出错误,而是可以输出到文件中 新建一个err_logginginfo.py文件: import logging logging.basicConfig(level=logging.INFO) s = '0' n = int(s) logging.info('n=%d' % n) print(10/n) #执行结果 PS E:\Python3.6.3\workspace>python err_loggingin...
import logging # 配置日志记录 logging.basicConfig(level=logging.DEBUG) def divide(x, y): assert y != 0, "除数不能为0" result = x / y return result # 使用断言进行除法运算 try: result = divide(10, 0) except AssertionError as e: logging.error("除法运算出错: %s", e) else: logging....
assert n != 0, 'n is zero!' AssertionError: n is zero! 1. 2. 3. 4. 5. 6. 7. 8. logging: 用logging代替print, 可将信息输出到文件中,但我还不懂是哪个文件,怎么找。。。 logging.info()可以输出一段文本,但并不会主动将文本信息显示在会话框,所以需要加: logging.basicConfig(level=logging...
assert 语句 assert断言语句的意思是,断定后边的句子是对的,否则就会有AssertionError抛出,并且给出逗号后边的信息,注意断言会抛出错误、打断程序,但是相比于print来输出信息的好处是可以自定义一些更详细的错误信息,往往在为了保证某些通常应该成立的条件时使用,比如一个卷积神经网络的输入矩阵的大小,可以在传入前使用asser...
1.1 assert 断言 Python的assert是用来检查一个条件,如果它为真,就不做任何事。如果它为假,则会抛出AssertError并且包含错误信息。例如: 代码语言:javascript 复制 py>x=23py>assert x>0,"x is not zero or negative"py>assert x%2==0,"x is not an even number"Traceback(most recent call last):File...
assert语句用于检查某个条件是否为真,如果为假,则引发AssertionError异常。它可用于调试和确保程序的正确性。 代码语言:python 代码运行次数:0 复制 Cloud Studio代码运行 defdivide_numbers(a,b):assertb!=0,"Cannot divide by zero."returna/btry:result=divide_numbers(10,0)exceptAssertionErrorase:print(f"Ass...
assertn!=0,'n is zero!' 单元测试 使用pytest进行单元测试 pip install pytest 撰写单元测试文件 文件名应以test_开头或以_test.py结尾 文件中类应以Test开头,方法以test_开头 预期内异常通过pytest.raises捕获 importpytestfromSingleLinkedListimportSingleLinkedListdeftest_remove(self):colors=SingleLinkedList()col...
assert 1 == 1 assert 1 == 2 1. 2. 3. part9:try..except的方式比较if的方式的好处 try..except这种异常处理机制就是取代if那种方式,让你的程序在不牺牲可读性的前提下增强健壮性和容错性 异常处理中为每一个异常定制了异常类型(python中统一了类与类型,类型即类),对于同一种异常,一个except就可以捕捉...
13.Python使用logging模块调试程序 14.Python IDLE调试程序 15.Python assert调试程序 第11章 Python模块和包 1.什么是模块 2.Python import导入模块 3.Python自定义模块 4.含有空格或以数字开头的模块名,应该如何引入? 5.Python name=='main’的作用是什么?