小码哥的IT人生

Python assert 关键字

Python基础 2022-06-06 16:25:33小码哥的IT人生shichen

Python assert 关键字

实例

测试条件是否返回 True:

x = "hello"
# 如果条件返回True,则什么也不会发生:
assert x == "hello"
#如果条件返回 False,则会引发 AssertionError:
assert x == "goodbye"

完整实例:

x = "hello"
#if condition returns True, then nothing happens:
assert x == "hello"
#if condition returns False, AssertionError is raised:
assert x == "goodbye"

定义和用法

assert 关键字在调试代码时使用。

assert 关键字使您可以测试代码中的条件是否返回 True,否则,程序将引发 AssertionError。

您可以编写一条若代码返回 False 时输出的消息,请看下面的例子。

更多实例

示例代码:

如果条件为 False,则写一条消息:

x = "hello"
# 如何条件返回 False,引发 AssertionError:
assert x == "goodbye", "x should be 'hello'"

完整实例:

x = "hello"
#if condition returns False, AssertionError is raised:
assert x == "goodbye", "x should be 'hello'"

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024