python3 中的assert函数

要用到的函数:

assert:

如果你断言的 语句正确 则什么反应都没有
但是如果你出错之后 就会报出 AssertionError 并且错误可以自己填写
格式 :
assert + 要判断语句 + 双引号“报错语句”

xdx = [1,2,3,4, 5]
xxx = 1
yyy = 6
assert xxx in xdx, f"{xxx} 不存在于 {xdx}"
assert yyy in xdx, "{yyy} 不存在于 {xdx}"
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
C:\Users\GEFREI~1\AppData\Local\Temp/ipykernel_20784/732228326.py in <module>
----> 1 assert yyy in xdx, "{yyy} 不存在于 {xdx}"
      2 assert yyy in xdx, f"{yyy} 不存在于 {xdx}"
AssertionError: {yyy} 不存在于 {xdx}
###加了f和{}之后就会保留格式
assert yyy in xdx, f"{yyy} 不存在于 {xdx}"
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
C:\Users\GEFREI~1\AppData\Local\Temp/ipykernel_20784/78607886.py in <module>
----> 1 assert yyy in xdx, f"{yyy} 不存在于 {xdx}"
AssertionError: 6 不存在于 [1, 2, 3, 4, 5]
###这样是不对的,不能有print
assert yyy in xdx, print(f"{yyy} 不存在于 {xdx}")
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
C:\Users\GEFREI~1\AppData\Local\Temp/ipykernel_20784/210735659.py in <module>
----> 1 assert yyy in xdx, print(f"{yyy} 不存在于 {xdx}")
AssertionError: None

补充:

对于上述{}的应用,更多请参照:
https://blog.csdn.net/ziluuu/article/details/104447756
(python对于格式的三种控制方法)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值