如何在python中正确使用断言?

2024-06-28 11:09:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python程序,在执行之前需要断言许多嵌套条件

Python有一种用assert语句断言的方法

Syntex:assert condition, error_message(optional)

但是,我需要断言多个嵌套条件,并且可能在断言中执行多个语句

在python中使用断言的正确方法是什么


我的想法是:只有当b > atrue时才检查c,只有检查a > c两者都为真。断言执行多个语句后,如:-记录信息和打印信息等

伪代码:

if c != null then
  if b > a then
    if a > c then
     print 'yippee!'
    else
     throw exception('a > c error')
  else
    throw exception('b > a error')
else
  throw exception('c is null')

Tags: 方法程序ifexceptionerrorassert断言语句
1条回答
网友
1楼 · 发布于 2024-06-28 11:09:22

你是说像这样的事吗

a = 1
b = 2
c = 3

assert b > a and c > b and a > c, 'Error: a is not greater than c'

输出:

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    assert b > a and c > b and a > c, 'Error: a is not greater than c'
AssertionError: Error: a is not greater than c

something like this:- check c only when b > a is true and check a > c only both are true. And after assertion executes multiple statements like:- log the info and print the info etc..

您可以一个接一个地使用多个assert语句,就像您将在每个语句下编写多个if语句一样,除非您必须考虑到您的assert会引发一个异常,您需要处理这个异常。通过这种方式,您可以简单地控制执行流,并打印/记录您需要的任何内容。。。例如,类似这样的事情:

def make_comperations(a, b, c = None): # note c is optional
  assert c is not None,  'Error: c is None'
  assert b > a, 'Error: a is not greater than b'
  assert c > a, 'Error: c is not greater than a'


try:
  make_comperations(1, 2, 3) # ok
  make_comperations(1, 2) # error
  make_comperations(1, 2, 0) # error, but won't be executed since the line above will throw an exception
  print("All good!")
except AssertionError as err:
  if str(err) == 'Error: c is None':
    print("Log: c is not given!")
  if str(err) == 'Error: a is not greater than b':
    print("Log: b > a error!")
  elif str(err) == 'Error: c is not greater than a':
    print("Log: c > a error!")

输出:

Log: c is not given!

相关问题 更多 >