8.函數(shù)
定義函數(shù)
defgreet_user():
print('hello!')
greet_user()
輸出結(jié)果:
hello!
可以向定義的函數(shù)傳遞參數(shù):
defgreet_user(username):
print(f"hello!{username}涩蜘!")
greet_user('jesse')
輸出結(jié)果:
hello决乎!jesse违柏!
在上述代碼中username稱(chēng)為形參吱型,jesse稱(chēng)為實(shí)實(shí)參存筏。實(shí)參分為位置實(shí)參和關(guān)鍵字實(shí)參碍岔,位置實(shí)參顧名思義與位置順序有關(guān)痴施,傳入的實(shí)參與定義中的形參所在的位置一一對(duì)應(yīng)擎厢。而關(guān)鍵字實(shí)參則是傳遞給函數(shù)的名值對(duì),直接將名稱(chēng)和值對(duì)應(yīng)起來(lái)辣吃。函數(shù)還會(huì)有默認(rèn)值动遭,在定義形參的時(shí)候,如果給了默認(rèn)值神得,那么在傳入實(shí)參的時(shí)候厘惦,首先,形參以位置對(duì)應(yīng)關(guān)系哩簿,當(dāng)對(duì)應(yīng)到關(guān)鍵字參數(shù)的時(shí)候宵蕉,如果傳入的參數(shù)沒(méi)有明確的值酝静,或者沒(méi)有傳入對(duì)應(yīng)的參數(shù),那就使用形式參數(shù)中的默認(rèn)值羡玛,所以這里可以得到有默認(rèn)值的參數(shù)是可選參數(shù)别智。
defdescribe_pet(pet_name,animal_type='dog'):
"""顯示寵物的信息"""
print(f"I have a {animal_type}!")
print(f"My {animal_type}'s name is {pet_name}")
describe_pet(pet_name='willie')
輸出結(jié)果:
Ihaveadog.
Mydog's name is Willie.
當(dāng)提供的參數(shù)多于或少于函數(shù)完成工作所需的實(shí)參數(shù)量的時(shí)候,將出現(xiàn)實(shí)參不匹配的現(xiàn)象稼稿,進(jìn)而引發(fā)報(bào)錯(cuò)薄榛。
定義的函數(shù)應(yīng)該都有返回值,由return語(yǔ)句完成让歼。
定義函數(shù)的時(shí)候敞恋,可以將定義的函數(shù)與循環(huán)、列表(或者列表的副本)等結(jié)合使用谋右,可以讓程序?qū)崿F(xiàn)更多的功能硬猫,符合解決生活實(shí)際問(wèn)題的需要。
*arg傳遞任意數(shù)量的實(shí)參倚评,在定義函數(shù)的時(shí)候傳入的值的數(shù)量不固定浦徊,能夠接受任意數(shù)量的值。
defmake_pizza(*toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
輸出結(jié)果:
('pepperoni')
('mushrooms','green peppers','extra cheese')
*arg結(jié)合位置實(shí)參使用:
defmake_pizza(size,*toppings):
print(f"making a {size}-inch pizza with the following toppings:")
fortoppingintoppings:
print(f"-{topping}")
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')
**arg接受任意數(shù)量的關(guān)鍵字參數(shù):
defbuild_profile(first,last,**user_info):
user_info['first_name'] =first
user_info['last_name'] =last
returnuser_info
user_profile=build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)
輸出結(jié)果:
{'location':'princeton','field':'physics','first_name':'albert','last_name':'einstein'}
函數(shù)可以被存儲(chǔ)在模塊之中天梧,模塊就是擴(kuò)展名為.py的文件盔性。在相同目錄下,如果一個(gè)文件想要使用一個(gè)模塊呢岗,需要使用import語(yǔ)句加上文件名來(lái)導(dǎo)入這個(gè)模塊冕香。這樣就可以使用這個(gè)模塊中的所有函數(shù)了。除了運(yùn)用import來(lái)導(dǎo)入模塊之外后豫,常見(jiàn)的用法還有:
frommodule_nameimportimportfunction_name
function_name()#直接從指定模塊中調(diào)用特定函數(shù)悉尾。
importmodule_name
module_name.function_name()#使用模塊名加.加函數(shù)名的方式調(diào)用指定函數(shù)
frommodule_nameimport*
#使用*號(hào),從模塊中導(dǎo)入所有的函數(shù)
function_name()
#這種方法存在一個(gè)弊端挫酿,如果程序中存在與調(diào)用函數(shù)重名的部分构眯,重復(fù)的部分可能會(huì)被覆蓋,影響程序的運(yùn)行早龟,因此最好的辦法就是使用上面兩種方法惫霸。
所有函數(shù)在編寫(xiě)過(guò)程中都需要注意只使用小寫(xiě)字母和下劃線,并且每個(gè)函數(shù)都要由注釋?zhuān)⑨寫(xiě)?yīng)該跟在函數(shù)定義后面葱弟,并采用文檔字符串的格式壹店。