1. <source id="nejs2"></source>
  2. <video id="nejs2"></video>
    <source id="nejs2"></source>
          1. 首頁 > Python 教程 > Python 提高教程 > Python assert語句

            Python assert語句

            更新:

            在 Python 中,如果給定條件評估為真,則使用assert語句繼續執行。 如果斷言條件評估為假,那么它會引發帶有指定錯誤消息的AssertionError異常。

            句法

            assert condition [, Error Message] 

            下面的示例演示了一個簡單的 assert 語句。

            Example: assert

            x = 10
            assert x > 0
            print('x is a positive number.') 

            Output

            x is a positive number. 

            在上面的例子中,斷言條件x > 0評估為真,因此它將繼續執行下一條語句,沒有任何錯誤。

            assert 語句可以選擇性地包含一個錯誤消息字符串,該字符串與AssertionError一起顯示。 考慮以下帶有錯誤消息的assert語句。

            Example: Assert Statement with Error Message

            x = 0
            assert x > 0, 'Only positive numbers are allowed'
            print('x is a positive number.') 

            Output

            Traceback (most recent call last):
                assert x > 0, 'Only positive numbers are allowed'
            AssertionError: Only positive numbers are allowed 

            以上,x=0,所以斷言條件x > 0變為假,所以它會用指定的消息“只允許正數”來引發AssertionError。 不執行print('x is a positive number.')語句。

            下面的示例在函數中使用了 assert 語句。

            Example: assert

            def square(x):
                assert x>=0, 'Only positive numbers are allowed'
                return x*x
            
            n = square(2) # returns 4
            n = square(-2) # raise an AssertionError 

            Output

            Traceback (most recent call last):
                assert x > 0, 'Only positive numbers are allowed'
            AssertionError: Only positive numbers are allowed 

            上圖中,square(2)將返回 4,而square(-2)將加注一個AssertionError,因為我們通過了-2。

            AssertionError也是一個內置的異常,可以使用 try 來處理-除了如下所示的構造:

            Example: AssertionError

            def square(x):
                assert x>=0, 'Only positive numbers are allowed'
                return x*x
            
            try:
                square(-2)
            except AssertionError as msg:
                print(msg) 

            Output

            Only positive numbers are allowed 

            上圖,調用square(-2)會引發AssertionError,由除塊處理。 assert 語句中的錯誤消息將作為參數傳遞給異常參數msg,使用as關鍵字。

            因此,assert 語句通常應該用于防止可能的錯誤,并指定適當的錯誤消息。****

            文章目錄
            頂部 久久久久99精品成人片毛片_黃色A片三級三級三級无码_日本不卡高清视频v中文字幕_高清欧美视频一区二区
            1. <source id="nejs2"></source>
            2. <video id="nejs2"></video>
              <source id="nejs2"></source>