簡介
def greet_user():
print("Hello!...")
greet_user()
Hello!...
向函數中傳遞信息
形參
:函數完成其工作所需的一項信息
實參
:是調用函數時傳遞給函數的信息
def greet_user(username): # username 變量爲 形參數
print("Hello " + username.title() + "!")
greet_user("mikowoo") # 'mikowoo' 爲實參
Hello Mikowoo!
傳遞實參
位置實參–關聯方式是實參的順序
位置實參的順序很重要
def describe_pet(animal_type,pet_name):
print("\n I hava a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('hamster','harry')
describe_pet('dog','willie')
I hava a hamster.
My hamster's name is Harry.
I hava a dog.
My dog's name is Willie.
關鍵字實參
關鍵字實參是傳遞給函數的名稱-值對. 因爲名稱和值關聯,因此向函數傳遞實參時不會混淆.
關鍵字實參可以無需考慮函數調用中的實參順序,還清楚地指出了函數調用中各個值得用途
使用關鍵字實參時,務必準確地指定函數定義中的形參名
def describe_pet(animal_type,pet_name):
print("\n I hava a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(animal_type='haster',pet_name='harry')
describe_pet(pet_name='harry',animal_type='haster')
I hava a haster.
My haster's name is Harry.
I hava a haster.
My haster's name is Harry.
默認值
編寫函數時,可給每個形參指定默認值
使用默認值時,在形參列表中必須先列出沒有默認值的形參,再列出有默認值的實參
def describe_pet(pet_name,animal_type='dog'):
print("\n I hava a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')
describe_pet('willie')
describe_pet(pet_name='harry',animal_type='hamster')
I hava a dog.
My dog's name is Willie.
I hava a dog.
My dog's name is Willie.
I hava a hamster.
My hamster's name is Harry.
讓實參變成可選
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)
Jimi Hendrix
John Lee Hooker
傳遞列表
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 = []
# 模擬打印每個設計,直達沒有未打印的設計爲止
while unprinted_designs:
current_design = unprinted_designs.pop()
print("Printing model: " + current_design)
completed_models.append(current_design)
# 顯示打印好的所有模型
print("\n The following models have been printed:")
for completed_model in completed_models:
print(completed_model)
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case
The following models have been printed:
dodecahedron
robot pendant
iphone case
使用函數實現
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)
def show_completed_models(completed_models):
print("\n The following models have been printed:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['iphone case','robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)
print(unprinted_designs)
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case
The following models have been printed:
dodecahedron
robot pendant
iphone case
[]
禁止函數修改列表
[:]
此切片表示法創建列表副本
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)
def show_completed_models(completed_models):
print("\n The following models have been printed:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['iphone case','robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_designs[:],completed_models)
show_completed_models(completed_models)
print(unprinted_designs)
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case
The following models have been printed:
dodecahedron
robot pendant
iphone case
['iphone case', 'robot pendant', 'dodecahedron']
傳遞任意數量的實參
*toppings
星號讓Python創建一個名爲toppings的空元組,並將收到的所有值封裝到這個元組中,即便函數只收到一個值亦是如此
def make_pizza(*toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')
def make_pizza(*toppings):
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
Making a pizza with the following toppings:
- pepperoni
Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
結合使用位置實參和任意數量實參
如果讓函數接受不同類型的實參,必須在函數定義中將接納任意數量實參的形參放在最後
python先匹配位置實參和關鍵字實參,再將餘下的實參都收集到最後一個形參中
def make_pizza(size,*toppings):
print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')
Making a 16-inch pizza with the following toppings:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
使用任意數量的關鍵字實參
**user_info
兩個星號讓Python創建一個名爲user_info的空字典,並將收到的所有名稱-值對都封裝到這個字典中
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_profile = build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
返回值
返回簡單值
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 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=''):
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}
結合使用函數和while循環
def get_formatted_name(first_name,last_name):
full_name = first_name + ' ' + last_name
return full_name.title()
# 無限循環
while True:
print("\n Please tell me your name:")
print("(enter 'q' at any time to quit)")
f_name = input("First name: ")
if f_name == 'q':
break
l_name = input("Last name: ")
if l_name == 'q':
break
formatted_name = get_formatted_name(f_name,l_name)
print("\n Hello, " + formatted_name + " !")
Please tell me your name:
(enter 'q' at any time to quit)
First name: eric
Last name: mattes
Hello, Eric Mattes !
Please tell me your name:
(enter 'q' at any time to quit)
First name: q
將函數存儲在模塊中
編寫函數,並保存爲 .py
的文件
def make_pizza(size,*toppings):
print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
導入整個模塊
import 模塊名
導入特定的函數
from module_name import function_name
使用 as 給函數指定別名
from pizza import make_pizza as mp
使用 as 給模塊指定別名
import pizza as p
導入模塊中的所有函數
from pizza import *
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')