如何在python中正确使用断言? [关闭]

问题描述 投票:0回答:1

我有一个python程序,在执行之前需要声明很多嵌套条件。

Python有一种使用assert语句进行断言的方法,

语法:assert condition, error_message(optional)

但是,我需要声明多个嵌套条件,并且可能在assert中执行多个语句。

在python中使用assert的正确方法是什么?


我的想法是:仅当cb > a时才检查true,而只有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')
python assert
1个回答
0
投票

您的意思是这样的吗?

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

类似这样:-仅当b> a为true时才检查c,而仅当a> c都为true时才检查。断言后执行多个语句,例如:-记录信息并打印信息等。

您可以一个接一个地使用多个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!
© www.soinside.com 2019 - 2024. All rights reserved.