Python基礎(chǔ)之函數(shù)用法實(shí)例詳解
本文以實(shí)例形式較為詳細(xì)的講述了Python函數(shù)的用法,對(duì)于初學(xué)Python的朋友有不錯(cuò)的借鑒價(jià)值。分享給大家供大家參考之用。具體分析如下:
通常來說,Python的函數(shù)是由一個(gè)新的語句編寫,即def,def是可執(zhí)行的語句--函數(shù)并不存在,直到Python運(yùn)行了def后才存在。
函數(shù)是通過賦值傳遞的,參數(shù)通過賦值傳遞給函數(shù)
def語句將創(chuàng)建一個(gè)函數(shù)對(duì)象并將其賦值給一個(gè)變量名,def語句的一般格式如下:
def <name>(arg1,arg2,arg3,……,argN): <statements>
def語句是實(shí)時(shí)執(zhí)行的,當(dāng)它運(yùn)行的時(shí)候,它創(chuàng)建并將一個(gè)新的函數(shù)對(duì)象賦值給一個(gè)變量名,Python所有的語句都是實(shí)時(shí)執(zhí)行的,沒有像獨(dú)立的編譯時(shí)間這樣的流程
由于是語句,def可以出現(xiàn)在任一語句可以出現(xiàn)的地方--甚至是嵌套在其他語句中:
if test:
def fun():
...
else:
def func():
...
...
func()
可以將函數(shù)賦值給一個(gè)不同的變量名,并通過新的變量名進(jìn)行調(diào)用:
othername=func() othername()
創(chuàng)建函數(shù)
內(nèi)建的callable函數(shù)可以用來判斷函數(shù)是否可調(diào)用:
>>> import math >>> x=1 >>> y=math.sqrt >>> callable(x) False >>> callable(y) True
使用del語句定義函數(shù):
>>> def hello(name):
return 'Hello, '+name+'!'
>>> print hello('world')
Hello, world!
>>> print hello('Gumby')
Hello, Gumby!
編寫一個(gè)fibnacci數(shù)列函數(shù):
>>> def fibs(num):
result=[0,1]
for i in range(num-2):
result.append(result[-2]+result[-1])
return result
>>> fibs(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> fibs(15)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
在函數(shù)內(nèi)為參數(shù)賦值不會(huì)改變外部任何變量的值:
>>> def try_to_change(n): n='Mr.Gumby' >>> name='Mrs.Entity' >>> try_to_change(name) >>> name 'Mrs.Entity'
由于字符串(以及元組和數(shù)字)是不可改變的,故做參數(shù)的時(shí)候也就不會(huì)改變,但是如果將可變的數(shù)據(jù)結(jié)構(gòu)如列表用作參數(shù)的時(shí)候會(huì)發(fā)生什么:
>>> name='Mrs.Entity' >>> try_to_change(name) >>> name 'Mrs.Entity' >>> def change(n): n[0]='Mr.Gumby' >>> name=['Mrs.Entity','Mrs.Thing'] >>> change(name) >>> name ['Mr.Gumby', 'Mrs.Thing']
參數(shù)發(fā)生了改變,這就是和前面例子的重要區(qū)別
以下不用函數(shù)再做一次:
>>> name=['Mrs.Entity','Mrs.Thing'] >>> n=name #再來一次,模擬傳參行為 >>> n[0]='Mr.Gumby' #改變列表 >>> name ['Mr.Gumby', 'Mrs.Thing']
當(dāng)2個(gè)變量同時(shí)引用一個(gè)列表的時(shí)候,它們的確是同時(shí)引用一個(gè)列表,想避免這種情況,可以復(fù)制一個(gè)列表的副本,當(dāng)在序列中做切片的時(shí)候,返回的切片總是一個(gè)副本,所以復(fù)制了整個(gè)列表的切片,將會(huì)得到一個(gè)副本:
>>> names=['Mrs.Entity','Mrs.Thing'] >>> n=names[:] >>> n is names False >>> n==names True
此時(shí)改變n不會(huì)影響到names:
>>> n[0]='Mr.Gumby' >>> n ['Mr.Gumby', 'Mrs.Thing'] >>> names ['Mrs.Entity', 'Mrs.Thing'] >>> change(names[:]) >>> names ['Mrs.Entity', 'Mrs.Thing']
關(guān)鍵字參數(shù)和默認(rèn)值
參數(shù)的順序可以通過給參數(shù)提供參數(shù)的名字(但是參數(shù)名和值一定要對(duì)應(yīng)):
>>> def hello(greeting, name):
print '%s,%s!'%(greeting, name)
>>> hello(greeting='hello',name='world!')
hello,world!!
關(guān)鍵字參數(shù)最厲害的地方在于可以在參數(shù)中給參數(shù)提供默認(rèn)值:
>>> def hello_1(greeting='hello',name='world!'):
print '%s,%s!'%(greeting,name)
>>> hello_1()
hello,world!!
>>> hello_1('Greetings')
Greetings,world!!
>>> hello_1('Greeting','universe')
Greeting,universe!
若想讓greeting使用默認(rèn)值:
>>> hello_1(name='Gumby') hello,Gumby!
可以給函數(shù)提供任意多的參數(shù),實(shí)現(xiàn)起來也不難:
>>> def print_params(*params):
print params
>>> print_params('Testing')
('Testing',)
>>> print_params(1,2,3)
(1, 2, 3)
混合普通參數(shù):
>>> def print_params_2(title,*params):
print title
print params
>>> print_params_2('params:',1,2,3)
params:
(1, 2, 3)
>>> print_params_2('Nothing:')
Nothing:
()
星號(hào)的意思就是“收集其余的位置參數(shù)”,如果不提供任何供收集的元素,params就是個(gè)空元組
但是不能處理關(guān)鍵字參數(shù):
>>> print_params_2('Hmm...',something=42)
Traceback (most recent call last):
File "<pyshell#112>", line 1, in <module>
print_params_2('Hmm...',something=42)
TypeError: print_params_2() got an unexpected keyword argument 'something'
試試使用“**”:
>>> def print_params(**params):
print params
>>> print_params(x=1,y=2,z=3)
{'y': 2, 'x': 1, 'z': 3}
>>> def parames(x,y,z=3,*pospar,**keypar):
print x,y,z
print pospar
print keypar
>>> parames(1,2,3,5,6,7,foo=1,bar=2)
1 2 3
(5, 6, 7)
{'foo': 1, 'bar': 2}
>>> parames(1,2)
1 2 3
()
{}
>>> def print_params_3(**params):
print params
>>> print_params_3(x=1,y=2,z=3)
{'y': 2, 'x': 1, 'z': 3}
>>> #返回的是字典而不是元組
>>> #組合‘#'與'##'
>>> def print_params_4(x,y,z=3,*pospar,**keypar):
print x,y,z
print pospar
print keypar
>>> print_params_4(1,2,3,5,6,7,foo=1,bar=2)
1 2 3
(5, 6, 7)
{'foo': 1, 'bar': 2}
>>> print_params_4(1,2)
1 2 3
()
{}
相信本文所述對(duì)大家Python程序設(shè)計(jì)的學(xué)習(xí)有一定的借鑒價(jià)值。
- Python基礎(chǔ)學(xué)習(xí)之常見的內(nèi)建函數(shù)整理
- 詳談Python基礎(chǔ)之內(nèi)置函數(shù)和遞歸
- Python 專題一 函數(shù)的基礎(chǔ)知識(shí)
- python基礎(chǔ)教程之匿名函數(shù)lambda
- 用Python進(jìn)行基礎(chǔ)的函數(shù)式編程的教程
- python基礎(chǔ)教程之自定義函數(shù)介紹
- Python3基礎(chǔ)之函數(shù)用法
- python基礎(chǔ)教程之popen函數(shù)操作其它程序的輸入和輸出示例
- Python 函數(shù)基礎(chǔ)知識(shí)匯總
相關(guān)文章
使用url_helper簡化Python中Django框架的url配置教程
這篇文章主要介紹了使用url_helper簡化Python中Django框架的url配置教程,需要的朋友可以參考下2015-05-05
用smtplib和email封裝python發(fā)送郵件模塊類分享
本文針對(duì)發(fā)郵件相關(guān)的操作進(jìn)行了封裝,包括發(fā)送文本、HTML、帶附件的郵件,使用Python發(fā)郵件,主要用到smtplib和email兩個(gè)模塊,需要的朋友可以參考下2014-02-02
圖文詳解如何利用PyTorch實(shí)現(xiàn)圖像識(shí)別
這篇文章主要給大家介紹了關(guān)于如何利用PyTorch實(shí)現(xiàn)圖像識(shí)別的相關(guān)資料,文中通過圖文以及實(shí)例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用PyTorch具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2023-04-04
Python+?Flask實(shí)現(xiàn)Mock?Server詳情
這篇文章主要介紹了Python+?Flask實(shí)現(xiàn)Mock?Server詳情,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09

