我正在 Python 3 中編寫一個名為 word_count 的函數(它接受一個我稱之為 my_string 的參數),它應該計算字符串中的單詞數。字符串可能包含多個空格的單詞(例如 hello there),并且該函數需要能夠計算出它是兩個單詞。我不應該使用任何內置的 Python 函數,如果我遇到任何錯誤,我也會使用 try-except(例如,如果感興趣的值不是字符串,除了將執行返回“不是字符串” ”我已經能夠編寫一個函數,并且我創建了一個名為 numspaces 的計數器變量,我已將其初始化為 0。然后我寫了 try,然后是一個帶有名為 current_character 的索引變量的 for 循環,它將遍歷 my_string 中的所有當前字符. 我寫了一個條件語句,如果 current_character 等于一個空格,numspaces 需要加一,numwords(我用來保持字符串中單詞總數的變量)等于 numspaces + 1。然后我寫一個 else if 語句,表示如果 numspaces 等于 0,numwords = 1 并返回 numwords。如果遇到錯誤,我寫了一個返回“不是字符串”的exceptdef word_count(my_string): numspaces = 0 try: for current_character in my_string: if current_character == " ": numspaces += 1 numwords = numspaces + 1 elif numspaces == 0: numwords = 1 return numwords except: return "Not a string"以下是一些測試用例,以及使用測試用例時的預期結果:Word Count: 4Word Count: 2Word Count: Not a stringWord Count: Not a stringWord Count: Not a stringprint("Word Count:", word_count("Four words are here!"))print("Word Count:", word_count("Hi David"))print("Word Count:", word_count(5))print("Word Count:", word_count(5.1))print("Word Count:", word_count(True))當我運行我編寫的代碼時,我得到以下輸出:Word Count: 4Word Count: 4Word Count: Not a stringWord Count: Not a stringWord Count: Not a string我不知道如何調整我的代碼來解釋測試用例 2(“嗨大衛”)
添加回答
舉報
0/150
提交
取消