python assert with and without parenthesis

后端 未结 5 924
南笙
南笙 2021-01-30 02:42

Here are four simple invocations of assert:

>>> assert 1==2
Traceback (most recent call last):
  File \"\", line 1, in ?
AssertionError

&g         


        
5条回答
  •  梦谈多话
    2021-01-30 03:31

    The last assert would have given you a warning (SyntaxWarning: assertion is always true, perhaps remove parentheses?) if you ran it through a full interpreter, not through IDLE. Because assert is a keyword and not a function, you are actually passing in a tuple as the first argument and leaving off the second argument.

    Recall that non-empty tuples evaluate to True, and since the assertion message is optional, you've essentially called assert True when you wrote assert(1==2, "hi").

提交回复
热议问题