断言是什么意思?它是如何使用的?


当前回答

>>>this_is_very_complex_function_result = 9
>>>c = this_is_very_complex_function_result
>>>test_us = (c < 4)

>>> #first we try without assert
>>>if test_us == True:
    print("YES! I am right!")
else:
    print("I am Wrong, but the program still RUNS!")

I am Wrong, but the program still RUNS!


>>> #now we try with assert
>>> assert test_us
Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    assert test_us
AssertionError
>>> 

其他回答

>>>this_is_very_complex_function_result = 9
>>>c = this_is_very_complex_function_result
>>>test_us = (c < 4)

>>> #first we try without assert
>>>if test_us == True:
    print("YES! I am right!")
else:
    print("I am Wrong, but the program still RUNS!")

I am Wrong, but the program still RUNS!


>>> #now we try with assert
>>> assert test_us
Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    assert test_us
AssertionError
>>> 

如果你想知道python中保留函数的确切功能,输入help(enter_keyword)

如果您正在输入保留关键字,请确保将其输入为字符串。

断言是在我们的程序中自信地陈述事实的语句。

语法:assert <条件>或assert <条件>,<错误消息>

它有一个条件/表达式,它应该总是为真。如果条件为false, assert语句将停止程序并抛出AssertionError错误消息。你的断言表达式将是你不希望在程序中出现的东西。

e.g.

Assert <条件>——使用Assert而没有<错误消息> var = int(输入("输入值1-9包含:")) 断言var != 0 打印(var) 输出: 如果输入为0: AssertionError 如果输入为1: 1 断言<条件>,<错误消息>——使用带有<错误消息>的断言 var = int(输入("输入值1-9包含:")) 断言var !=0,"输入不能为零" 打印(var) 输出: 如果输入为0: AssertionError:输入不能为零 如果输入为1: 1

重点:

它被用作调试工具。 它接受一个表达式和一个可选消息。 它几乎存在于每一种编程语言中

Python assert基本上是一种调试辅助工具,用于测试代码内部自检的条件。 当代码进入不可能的边缘情况时,Assert使调试变得非常容易。断言检查那些不可能的情况。

假设有一个函数计算商品折扣后的价格:

def calculate_discount(price, discount):
    discounted_price = price - [discount*price]
    assert 0 <= discounted_price <= price
    return discounted_price

这里,discounted_price永远不能小于0并且大于实际价格。因此,如果上述条件被违反,assert将引发断言错误,这有助于开发人员识别发生了不可能的事情。

希望能有所帮助。

这是一个简单的例子,保存到文件(比如b.py)

def chkassert(num):
    assert type(num) == int


chkassert('a')

当$python b.py

Traceback (most recent call last):
  File "b.py", line 5, in <module>
    chkassert('a')
  File "b.py", line 2, in chkassert
    assert type(num) == int
AssertionError