開始使用免費開始

使用 try-except 進行錯誤處理

在撰寫自己的函式時,一個好習慣是預先思考其他人(或你自己不小心誤用時)可能會如何使用你定義的函式。

就像前一個練習所示,len() 函式可以處理字串、list 和 tuple 等輸入參數,但無法處理 int 型別;當遇到無效輸入參數時,會拋出對應的錯誤與錯誤訊息。實作方式之一就是使用 try-except 區塊進行例外處理。

在這個練習中,你會定義一個函式,並使用 try-except 區塊來處理傳入不正確輸入參數的情況。

回想你在前面練習定義過的 shout_echo() 函式;範例程式碼已提供部分函式定義。你的目標是完成函式定義中的例外處理程式碼,並在拋出錯誤時提供合適的錯誤訊息。

本練習屬於課程

Python 函式入門

檢視課程

練習說明

  • 將變數 echo_wordshout_words 初始化為空字串。
  • 在例外處理區塊的適當位置加入關鍵字 tryexcept
  • 使用運算子 *word1 複製 echo 次並連接起來。將結果指定給 echo_word
  • 將字串 '!!!' 連接到 echo_word 後方。將結果指定給 shout_words

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Define shout_echo
def shout_echo(word1, echo=1):
    """Concatenate echo copies of word1 and three
    exclamation marks at the end of the string."""

    # Initialize empty strings: echo_word, shout_words
    
    

    # Add exception handling with try-except
    ____:
        # Concatenate echo copies of word1 using *: echo_word
        echo_word = ____

        # Concatenate '!!!' to echo_word: shout_words
        shout_words = ____
    ____:
        # Print error message
        print("word1 must be a string and echo must be an integer.")

    # Return shout_words
    return shout_words

# Call shout_echo
shout_echo("particle", echo="accelerator")
編輯並執行程式碼