文章目錄
- 定義函數
- 傳遞參數
- 傳回值
- 傳遞清單
- 将函數存儲在子產品中
定義函數
下面是一個簡單的函數,名為greet_user():
def greet_user():
"""簡單的問候語"""
print("Hi!")
greet_user()
python使用關鍵字def來定義一個函數。函數名為greet_user(),它不需要任何資訊就能完成其工作,是以括号是空的(即便如此,括号也必不可少)。最後,定義以冒号結尾。後面的所有縮進行構成了函數體。
傳遞參數
如下:
可在函數定義def greet_user()的括号内添加username。通過在這裡添加username,就可讓函數接受你給username指定的任何值。現在,這個函數要求你調用它時給username指定一個值。
在上述函數中,變量username是一個形參——函數完成其工作所需要的一項資訊。在調用時,“kk”是一個實參,是函數調用時傳遞給函數的資訊。
對于實參的傳遞方式有以下幾種:
位置實參
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')
'''
輸出:
I have a hamster.
My hamster's name is Harry.
'''
關鍵字實參
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(animal_type='hamster', pet_name='harry')
預設值
def describe_pet(pet_name, animal_type='dog'):
"""顯示寵物的資訊"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')
'''
輸出:
I have a dog.
My dog's name is Willie.
'''
傳回值
函數并非總是直接顯示輸出,相反,它可以處理一些資料,并傳回一個或一組值。函數傳回的值被稱為傳回值。在函數中,可使用return語句将值傳回到調用函數的代碼行。傳回值讓你能夠将程式的大部分繁重工作移到函數中去完成,進而簡化主程式。
傳回簡單值
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)
'''
輸出:
Jimi Hendrix
'''
可選的實參:
def get_formatted_name(first_name, last_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()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
傳回字典
def build_person(first_name, last_name):
"""傳回一個字典,其中包含有關一個人的資訊"""
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
傳遞清單
def greet_users(names):
"""向清單中的每位使用者都發出簡單的問候"""
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
'''
輸出:
Hello, Hannah!
Hello, Ty!
Hello, Margot!
'''
在函數中修改清單
例如:
# 首先建立一個清單,其中包含一些要列印的設計
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
# 模拟列印每個設計,直到沒有未列印的設計為止
# 列印每個設計後,都将其移到清單completed_models中
while unprinted_designs:
current_design = unprinted_designs.pop()
#模拟根據設計制作3D列印模型的過程
print("Printing model: " + current_design)
completed_models.append(current_design)
# 顯示列印好的所有模型
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
禁止函數修改清單
解決這個問題,可向函數傳遞清單的副本而不是原件;這樣函數所做的任何修改都隻影響副本,而絲毫不影響原件。
如:
傳遞任意數量的實參
def make_pizza(*toppings):
"""列印顧客點的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
'''
輸出:
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')
'''
将函數存儲在子產品中
導入整個子產品
如:我們将檔案pizza.py中除函數make_pizza()之外的其他代碼都删除:
def make_pizza(size, *toppings):
"""概述要制作的比薩"""
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
接下來,我們在pizza.py所在的目錄中建立另一個名為making_pizzas.py的檔案,這個檔案導入剛建立的子產品,再調用make_pizza()兩次:
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
Python讀取這個檔案時,代碼行import pizza讓Python打開檔案pizza.py,并将其中的所有函數都複制到這個程式中。你看不到複制的代碼,因為這個程式運作時, Python在幕後複制這些代碼。你隻需知道,在making_pizzas.py中,可以使用pizza.py中定義的所有函數。
導入特定函數
from module_name import function_name
from module_name import function_0, function_1, function_2
使用 as 給函數指定别名
from module_name import function_name as fn
使用 as 給子產品指定别名
import module_name as mn
導入子產品中的所有函數
from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')