6.1 定義函式
def greet_user():
"""顯示簡單的問候語"""
print('Hello!')
greet_user() # 呼叫函式
6.1.1 向函式傳遞資訊
def greet_user(username):
"“顯示簡單的問候語"”
print(f"Hello,{username.title()}!")
greet_user('jesse')
6. 2 實參和形參
6.2.1 位置實參
基於實參的順序在函式呼叫時把每個實參關聯到函式定義中的形參
def describe_pet(animal_type,pet_name):
"""顯示寵物的資訊"""
print(f"{\nI have a (animal_type).")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('hamster','harry’)
6.2.2 關鍵字實參
def describe_pet(animal_type,pet_name):
"""顯示寵物的資訊"""
print(f"{\nI have a (animal_type).")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(animal_type='hamster',pet_name='harry’)
6.2.3 預設值
在呼叫函式時,給形參提供了實參,python就使用你指定的實參值。你沒有給形參提供實參,就使用形參預設值
可給每個形參指定預設值。給animal_ype形參指定預設值dog
def describe_pet(animal_type,pet_name='dog’):
"""顯示寵物的資訊"""
print(f"{\nI have a (animal_type).")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(animal_type='willie')
# 也可以這樣describe_pet('willie')
6.2.4 讓實參變得可選
def get_formatted_name(first_name,last_name,middle_name=' '):
"""返回整潔的姓名"""
#檢查是否提供了中間名
if middle_name:
full_name F"{first_name} {middle_name} {last_name}"
else:
full_name =f"{first_name} {last_name}"
return full_name.title()
musician = get_formatted_name('jimi','hendrix')
print(musician)
musician = get_formatted_name('john','hooker','lee')
print(musician)
6.2.5 返回字典
def build_person(first_name,last_name):
"返回一個字典,其中包含有關一個人的資訊"
person ={'first':first_name,'last':last_name}
return person
musician = build_person('jimi','hendrix)
print(musician)
# (‘first':'jimi','last':'hendrix')
def build_person(first_name,last_name,age=None):
"返回一個字典,其中包含有關一個人的資訊。"
person =['first':first_name,'last':last_name)
if age:
person['age]=age
return person
musician build_person('jimi','hendrix',age=27)
print(musician)
# ('first':'jimi','last':'hendrix','age':27)
6.3 傳遞列表
6.3.1 在函式中修改列表
def print_models(unprinted_designs,completed_models):
while unprinted designs:
current design unprinted designs.pop()
print(f"Printing model:{current_design}")
completed_models.append(current_design)
def show_completed_models(completed_models):
“顯示列印好的所有模型."
print("\nThe following models have been printed:"
for completed_model in completed models:
print(completed_model)
unprinted designs ['phone case','robot pendant','dodecahedron']
completed models =[]
print_models(unprinted designs,completed models)
show_completed_models(completed_models)
6.3.2 禁止函式修改列表
# 將列表的副本傳遞給函式
# function_name(list_name[:])
# 在上一例子中
print_models(unprinted designs[:],completed models)
# 原列表就不會變為空值
6.4 傳遞任意數量的實參
形參名*toppings中的星號讓Python創健一個名為toppings的空元組,並將收到的所有值都封裝到這個元組中。
def make pizza(toppings):
# 列印顧客點的所有配料
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
# 上一句會報錯,賦予實參過多
def make pizza(*toppings):
# 實參前加*便可賦予任意量
6.4.1 結合使用位置實參和任意數量實參
def make_pizza(size,* toppings): # * toppings要寫在後面
“列印顧客點的所有配料”
print(f"\nMaking a (size)-inch pizza with the following toppings:
for topping in toppings:
print(f"-(topping)")
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms,'green peppers','extra cheese')
6.4.2 使用任意數量的關鍵字實參
形參*use_info中的兩個星號讓Python建立一個名為user_info的空字典,並將收到的所有名稱值對都放到這個字典中。在這個函式中,可以像訪問其他字典那樣訪問user info中的名稱值對。
def build profile(first,last,**user info):
# 建立一個字典,其中包含我們知道的有關使用者的一切
user info['first name']=first
user_info['last_name']=last
return user info
user_profile=build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)
# {location':'princeton','field':'physics','first_name':'albert','last_name':'einstein'}