開始使用免費開始

可變數量的位置引數

來練習可變數量的位置引數吧。你的任務是定義函式 sort_types()。它會接受不定數量的位置引數,並檢查每個引數是數字還是字串。接著,將檢查後的項目放入 numsstrings 清單。最後,函式回傳一個包含這兩個清單的 tuple。

使用 Python 內建的 isinstance() 來檢查物件是否為某一型別(例如 isinstance(1, int) 會回傳 True),或是否屬於數個型別其中之一(例如 isinstance(5.65, (int, str)) 會回傳 False)。

本題需要用到的型別為 intfloatstr

本練習屬於課程

Python 程式面試題實作練習

檢視課程

練習說明

  • 定義可接受任意數量引數的函式。
  • 檢查 arg 是否為數字,必要時將它加入 nums
  • 檢查 arg 是否為字串,必要時將它加入 strings

動手互動練習

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

# Define the function with an arbitrary number of arguments
def sort_types(____):
    nums, strings = [], []    
    for arg in args:
        # Check if 'arg' is a number and add it to 'nums'
        if ____:
            nums.____
        # Check if 'arg' is a string and add it to 'strings'
        elif ____:
            strings.____
    
    return (nums, strings)
            
print(sort_types(1.57, 'car', 'hat', 4, 5, 'tree', 0.89))
編輯並執行程式碼