1寄锐、傳遞實參
1.1 位置實參
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 ahamster.
????My hamster's name is Harry.
注意:函數調用中實參的順序與函數定義中形參的順序一致
1.2 關鍵字實參
describe_pet(animal_type='hamster',pet_name='harry')
describe_pet(pet_name='harry',animal_type='hamster')
-->I have ahamster.
????My hamster's name is Harry.
????I have ahamster.
????My hamster's name is Harry.
注意:使用關鍵字實參時袱耽,務必準確地指定函數定義中的形參名
1.3 默認值
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.
注意:在調用函數中給形參提供了實參時粗恢,Python將使用指定的實參值;否則捣炬,將使用形參的默認值批幌。在使用默認值時沙廉,在形參列表中必須先列出沒有默認值的形參翎猛,再列出有默認值的實參瓢捉,這讓python能正確解讀位置實參。
2办成、返回值
2.1 返回簡單值
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
2.2 讓實參變得可選
def get_formatted_name(first_name,last_name,middle_name=''):? ? //先讓中間名字形參默認為空
if middle_name:? ? //用if語句判斷
????full_name=first_name+" "+middle_name+" "+last_name? ? //有中間名字時加上實參
else:
????full_name=first_name+" "+last_name
return full_name.title()
musician=get_formatted_name('jimi','hendrix2')
print(musician)
musician=get_formatted_name('john','hooker','lee')
print(musician)
-->Jimi Hendrix2
????John Lee Hooker
2.3 返回字典
def build_person(first_name,last_name):
????person={'first':first_name,'last':last_name}
????return person
musician=build_person('tom','smith')
print(musician)
-->{'first': 'tom', 'last': 'smith'}
3、傳遞列表
def greet_users(names):? ? //形參是一個列表
????for name in names:
????????msg="Hello, "+name.title()+"!"
????????print(msg)
usernames=['hahana','ty','margot']
greet_users(usernames)
-->Hello, Hahana!
????Hello, Ty!
????Hello, Margot!
3.1 在函數中修改列表
def print_models(unprinted_designs,completed_models):
????while unprinted_designs:
????????current_design=unprinted_designs.pop()
????????print("Printiing 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=['iphone case','robot pendant','dodecahedron']
completed_models=[]
print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)
-->Printiing model: dodecahedron? ? //每個函數只負責一項具體的工作
????Printiing model: robot pendant
????Printiing model: iphone case
????The following models have been printed:
????dodecahedron
????robot pendant
????iphone case
4搂漠、傳遞任意數量的實參
def make_pizza(*toppings):? ? //形參*toppings中的星號讓Python創(chuàng)建一個名為toppings的空元組
????print(toppings)? ??
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
-->('pepperoni',)
????('mushrooms', 'green peppers', 'extra cheese')
4.1 結合使用位置參數和任意數量實參
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
4.2 使用任意數量的關鍵字實參
def build_profile(first,last,**user_info):? ? #形參**user_info中的兩個星號讓Python創(chuàng)建一個空字典迂卢,須放于形參最后位置
????profile={}
????profile['first-name']=first
????profile['last-name']=last
????for k,v in user_info.items():
????????profile[k]=v
? ? return profile
a=build_profile('albert','einstein',location='princeton',field='physics')
print(a)
-->{'first-name': 'albert', 'last-name': 'einstein', 'location': 'princeton', 'field': 'physics'}
5、將函數存儲在模塊中
5.1 導入整個模塊
pizza.py
def make_pizza(size,*toppings):
????print("\nMaking a "+str(size)+"-inch pizza with the following toppings:")
????for topping in toppings:
????????print("-"+topping)
同目錄下making_pizza.py
import pizza? ? ?//引用pizza則pizza.py中所有函數都能用
pizza.make_pizza(16,'pepperoni')
pizza.make_pizza(12,'mushrooms','green peppers','extra cheese')
5.2 導入特定的函數
from module_name import function_name
通過用逗號分隔函數名桐汤,導入任意數量的函數
from module_name import function_0而克,function_1,function_2
5.3 使用as給函數指定別名
from module_name import function_name as fn
5.4 使用as給模塊指定別名
import module_name as mn
5.5 導入模塊中的所有函數
from module_name import *? ? #星號(*)運算符可導入模塊中的所有函數
注意:所有的import語句都應放在文件開頭,唯一例外的情形是怔毛,在文件開頭使用了注釋來描述整個程序