Python 入門日記(八)—— 函式
阿新 • • 發佈:2020-07-15
2020.07.14 Python 入門的 Day7
成就:函式及其模組化
- 以下是 Python 中很簡單的一個函式及其呼叫。
def greet_user(): print("Hello!") # def 定義一個函式 greet_user() # 呼叫這個函式
- 通過給予函式形參,可給函式提供資訊。
def greet_user(username): print("Hello, " + username.title() + "!") # username 是傳遞給函式的形參 greet_user('jesse')
- 當向函式傳遞多個引數時,要注意呼叫函式時兩個引數的位置。
def describe_pet(animal_type, pet_name): print("\nI have a " + animal_type + ".") print("My " + animal_type + "'s name is " + pet_name.title() + '.') # 函式包含兩個形參 describe_pet('hamster', 'harry') describe_pet('dog', 'willie') # 注意位置實參的順序 describe_pet(animal_type= 'hamster', pet_name= 'harry') describe_pet(pet_name= 'harry', animal_type= 'hamster') # 提供關鍵字實參可不必保證順序一致
- 編寫函式時,可給每個形參以預設值,當不提供實參時,其值就為預設值。
def describe_pet(pet_name, animal_type= 'dog'): print("\nI have a " + animal_type + ".") print("My " + animal_type + "'s name is " + pet_name.title() + ".") # animal_type 的預設值為 'dog'describe_pet('whillie') describe_pet(pet_name= 'whillie') # 默認了 animal_type 的值為'dog'
- 注意,這裡修改了形參的順序。因為如果函式呼叫時只提供一個實參,那麼這個實參應該傳遞給 pet_name,
- 而非 animal_type,因此要把 pet_type 放到第一個。
- 函式並非簡單的顯示輸出,還可以返回值,理論上,返回值可以是任意型別。
def get_formatted_name(first_name, last_name): full_name = first_name + " " + last_name return full_name.title() # 返回一個字串 musician = get_formatted_name('jimi', 'hendrix') print(musician)
- 有時候我們需要讓實參變為可選的,就需要將可選的那個形參的預設值為空。
def Get_formatted_name(first_name, last_name, middle_name=''): # 並不是每個人都有中間名,因此 middle_name 是可選的,設為空字串 if middle_name: full_name = first_name + " " + middle_name + " " + last_name else: full_name = first_name + ' ' + last_name return full_name.title() # 根據 middle_name 是否為空判斷有沒有輸入中間名 musician = Get_formatted_name('jimi', 'hendrix') print(musician)
- 有時候向一個函式傳遞列表很有用,但不同的格式會不同的效果。
def print_models(unprinted_designs, completed_models): while unprinted_designs: current_design = unprinted_designs.pop() print("Printing model: " + current_design) completed_models.append(current_design) # 向 print_modelsa 傳遞兩個列表 def show_completed_models(completed_models): print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model) # 向 show_completed 傳遞兩個列表 unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] completed_models = [] print_models(unprinted_designs, completed_models) show_completed_models(completed_models) # 但這裡要注意的是 # 經過函式的處理,原來的兩個列表也發生了永久性的變化 # 不再是傳遞給函式之前的樣子了
function_name(list_name[:]) # 如果在呼叫函式的時候用切片法建立一個列表的副本 # 那麼原來的列表的值就不會被修改 # 例如: print_models(unprinted_designs, completed_models) # 函式執行結束後,unprinted_designs 的值就不會發生改變 # 而 completed_models 的值就會發生改變
- 有時候我們不知道函式需要接受多少個實參,但 Python 允許傳遞任意數量的實參。
def make_pizza(*toppings): print(toppings) # 用 * 標記的 toppings 表示一個元組,用來儲存任意數量的實參 # 在 Python 內部,任意數量的實參都以元組的形式儲存 make_pizza('pepperoni') make_pizza('mushrooms', 'green peppers', 'extra cheese')
- 在呼叫上述 Python 程式碼中的 toppings 裡面的資料,要用元組的方法。
def make_pizza2(*toppings): print("\nMaking a pizza with the following toppings:") for topping in toppings: print("-" + topping) # 向呼叫元組一樣呼叫 toppings
- 如果要讓函式接受不同型別的實參,必須要把接納任意數量實參的形參放到最後。
def make_pizza3(size, *toppings): print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("- " + topping) # *toppings 在最後 make_pizza3(16, 'pepperoni') make_pizza3(12, 'mushrooms', 'green peppers', 'extra cheese')
- 使用任意數量的關鍵字實參,可使函式能接受任意數量的鍵—值對。
def build_profile(first, last, **user_info): profile = {} profile['first_name'] = first profile['last_name'] = last for key, value in user_info.items(): profile[key] = value return profile # **user_info 表示一個能接納任意數量的鍵—值對的字典 user_profile = build_profile('albert', 'einstein', location= 'princeton', field= 'physics') # 提供鍵值對的格式 鍵=值 print(user_profile)
- 函式的優點之一是可將他們的程式碼與主程式分離,稱為模組化。
- 模組化的第一步是將函式儲存在模組中。
# 這是一個名為 pizza.py 的檔案 # 這個檔案中只有定義一個函式的程式碼 def make_pizza(size, *toppings): print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("- " + topping)
- 第二步是在其他程式中匯入模組。
# 這是一個與 pizza.py 在同一個資料夾下的 .py 檔案 import pizza # 這個語句會讓 Python 開啟 pizza.py 並將其中的所有函式匯入到此程式 pizza.make_pizza(16, 'pepperoni') pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') # 呼叫時要注意加上 pizza.
# 這是另一種匯入方式 from pizza import make_pizza # 將 pizza.py 的函式 make_pizza 匯入到此函式 make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') # 呼叫時就不需要新增其他的字首了
# 這是在匯入的同時加上別名,用 as 語句 from pizza import make_pizza as mp mp(16, 'pepperoni') mp(12, 'mushrooms', 'green peppers', 'extra cheese')
import pizza as p # 這也是新增別名 p.make_pizza(16, 'pepperoni') p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
from pizza import * # 這個語句是將 pizza.py 中的所有函式都複製過來 make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') # 呼叫時同樣不需要加字首