Python入門篇之函數(shù)
Pythond 的函數(shù)是由一個(gè)新的語句編寫,即def,def是可執(zhí)行的語句--函數(shù)并不存在,直到Python運(yùn)行了def后才存在。
函數(shù)是通過賦值傳遞的,參數(shù)通過賦值傳遞給函數(shù)
def語句將創(chuàng)建一個(gè)函數(shù)對(duì)象并將其賦值給一個(gè)變量名,def語句的一般格式如下:
def function_name(arg1,arg2[,...]):
statement
[return value]
返回值不是必須的,如果沒有return語句,則Python默認(rèn)返回值None。
函數(shù)名的命名規(guī)則:
函數(shù)名必須以下劃線或字母開頭,可以包含任意字母、數(shù)字或下劃線的組合。不能使用任何的標(biāo)點(diǎn)符號(hào);
函數(shù)名是區(qū)分大小寫的。
函數(shù)名不能是保留字。
Python使用名稱空間的概念存儲(chǔ)對(duì)象,這個(gè)名稱空間就是對(duì)象作用的區(qū)域, 不同對(duì)象存在于不同的作用域。下面是不同對(duì)象的作用域規(guī)則:
每個(gè)模塊都有自已的全局作用域。
函數(shù)定義的對(duì)象屬局部作用域,只在函數(shù)內(nèi)有效,不會(huì)影響全局作用域中的對(duì)象。
賦值對(duì)象屬局部作用域,除非使用global關(guān)鍵字進(jìn)行聲明。
LGB規(guī)則是Python查找名字的規(guī)則,下面是LGB規(guī)則:
1.大多數(shù)名字引用在三個(gè)作用域中查找:先局部(Local),次之全局(Global),再次之內(nèi)置(Build-in)。
>>> a=2
>>> b=2
>>> def test(b):
... test=a*b
... return test
>>>print test(10)
20
b在局部作用域中找到,a在全局作用域中找到。
2.如想在局部作用域中改變?nèi)肿饔糜虻膶?duì)象,必須使用global關(guān)鍵字。
#沒用global時(shí)的情況
>>> name="Jims"
>>> def set():
... name="ringkee"
...
>>> set()
>>> print name
Jims
#使用global后的情況
>>> name="Jims"
>>> def set1():
... global name
... name="ringkee"
...
>>> set1()
>>> print name
ringkee
3.'global'聲明把賦值的名字映射到一個(gè)包含它的模塊的作用域中。
函數(shù)的參數(shù)是函數(shù)與外部溝通的橋梁,它可接收外部傳遞過來的值。參數(shù)傳遞的規(guī)則如下:
4.在一個(gè)函數(shù)中對(duì)參數(shù)名賦值不影響調(diào)用者。
>>> a=1
>>> def test(a):
... a=a+1
... print a
...
>>> test(a)
2
>>> a
1 # a值不變
5.在一個(gè)函數(shù)中改變一個(gè)可變的對(duì)象參數(shù)會(huì)影響調(diào)用者。
>>> a=1
>>> b=[1,2]
>>> def test(a,b):
... a=5
... b[0]=4
... print a,b
...
>>> test(a,b)
5 [4, 2]
>>> a
1
>>> b
[4, 2] # b值已被更改
參數(shù)是對(duì)象指針,無需定義傳遞的對(duì)象類型。如:
>>> def test(a,b):
... return a+b
...
>>> test(1,2) #數(shù)值型
3
>>> test("a","b") #字符型
'ab'
>>> test([12],[11]) #列表
[12, 11]
函數(shù)中的參數(shù)接收傳遞的值,參數(shù)可分默認(rèn)參數(shù),如:
def function(ARG=VALUE)
元組(Tuples)參數(shù):
def function(*ARG)
字典(dictionary)參數(shù):
def function(**ARG)
一些函數(shù)規(guī)則:
默認(rèn)值必須在非默認(rèn)參數(shù)之后;
在單個(gè)函數(shù)定義中,只能使用一個(gè)tuple參數(shù)(*ARG)和一個(gè)字典參數(shù)(**ARG)。
tuple參數(shù)必須在連接參數(shù)和默認(rèn)參數(shù)之后。
字典參數(shù)必須在最后定義。
1.常用函數(shù)
1.abs(x)
abs()返回一個(gè)數(shù)字的絕對(duì)值。如果給出復(fù)數(shù),返回值就是該復(fù)數(shù)的模。
>>>print abs(-100)
100
>>>print abs(1+2j)
2.2360679775
2.callable(object)
callable()函數(shù)用于測試對(duì)象是否可調(diào)用,如果可以則返回1(真);否則返回0(假)??烧{(diào)用對(duì)象包括函數(shù)、方法、代碼對(duì)象、類和已經(jīng)定義了“調(diào)用”方法的類實(shí)例。
>>> a="123"
>>> print callable(a)
0
>>> print callable(chr)
1
3.cmp(x,y)
cmp()函數(shù)比較x和y兩個(gè)對(duì)象,并根據(jù)比較結(jié)果返回一個(gè)整數(shù),如果x<y,則返回-1;如果x>y,則返回1,如果x==y則返回0。
>>>a=1
>>>b=2
>>>c=2
>>> print cmp(a,b)
-1
>>> print cmp(b,a)
1
>>> print cmp(b,c)
0
4.divmod(x,y)
divmod(x,y)函數(shù)完成除法運(yùn)算,返回商和余數(shù)。
>>> divmod(10,3)
(3, 1)
>>> divmod(9,3)
(3, 0)
5.isinstance(object,class-or-type-or-tuple) -> bool
測試對(duì)象類型
>>> a='isinstance test'
>>> b=1234
>>> isinstance(a,str)
True
>>> isinstance(a,int)
False
>>> isinstance(b,str)
False
>>> isinstance(b,int)
True
下面的程序展示了isinstance函數(shù)的使用:
def displayNumType(num):
print num, 'is',
if isinstance(num, (int, long, float, complex)):
print 'a number of type:', type(num).__name__
else:
print 'not a number at all!!!'
displayNumType(-69)
displayNumType(9999999999999999999999999L)
displayNumType(565.8)
displayNumType(-344.3+34.4j)
displayNumType('xxx')
代碼運(yùn)行結(jié)果如下:
-69 is a number of type: int
9999999999999999999999999 is a number of type: long
565.8 is a number of type: float
(-344.3+34.4j) is a number of type: complex
xxx is not a number at all!!!
6.len(object) -> integer
len()函數(shù)返回字符串和序列的長度。
>>> len("aa")
2
>>> len([1,2])
2
7.pow(x,y[,z])
pow()函數(shù)返回以x為底,y為指數(shù)的冪。如果給出z值,該函數(shù)就計(jì)算x的y次冪值被z取模的值。
>>> print pow(2,4)
16
>>> print pow(2,4,2)
0
>>> print pow(2.4,3)
13.824
8.range([lower,]stop[,step])
range()函數(shù)可按參數(shù)生成連續(xù)的有序整數(shù)列表。
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10,2)
[1, 3, 5, 7, 9]
9.round(x[,n])
round()函數(shù)返回浮點(diǎn)數(shù)x的四舍五入值,如給出n值,則代表舍入到小數(shù)點(diǎn)后的位數(shù)。
>>> round(3.333)
3.0
>>> round(3)
3.0
>>> round(5.9)
6.0
10.type(obj)
type()函數(shù)可返回對(duì)象的數(shù)據(jù)類型。
>>> type(a)
<type 'list'>
>>> type(copy)
<type 'module'>
>>> type(1)
<type 'int'>
11.xrange([lower,]stop[,step])
xrange()函數(shù)與range()類似,但xrnage()并不創(chuàng)建列表,而是返回一個(gè)xrange對(duì)象,它的行為與列表相似,但是只在需要時(shí)才計(jì)算列表值,當(dāng)列表很大時(shí),這個(gè)特性能為我們節(jié)省內(nèi)存。
>>> a=xrange(10)
>>> print a[0]
0
>>> print a[1]
1
>>> print a[2]
2
2.內(nèi)置類型轉(zhuǎn)換函數(shù)
1.chr(i)
chr()函數(shù)返回ASCII碼對(duì)應(yīng)的字符串。
>>> print chr(65)
A
>>> print chr(66)
B
>>> print chr(65)+chr(66)
AB
2.complex(real[,imaginary])
complex()函數(shù)可把字符串或數(shù)字轉(zhuǎn)換為復(fù)數(shù)。
>>> complex("2+1j")
(2+1j)
>>> complex("2")
(2+0j)
>>> complex(2,1)
(2+1j)
>>> complex(2L,1)
(2+1j)
3.float(x)
float()函數(shù)把一個(gè)數(shù)字或字符串轉(zhuǎn)換成浮點(diǎn)數(shù)。
>>> float("12")
12.0
>>> float(12L)
12.0
>>> float(12.2)
12.199999999999999
4.hex(x)
hex()函數(shù)可把整數(shù)轉(zhuǎn)換成十六進(jìn)制數(shù)。
>>> hex(16)
'0x10'
>>> hex(123)
'0x7b'
5.long(x[,base])
long()函數(shù)把數(shù)字和字符串轉(zhuǎn)換成長整數(shù),base為可選的基數(shù)。
>>> long("123")
123L
>>> long(11)
11L
6.list(x)
list()函數(shù)可將序列對(duì)象轉(zhuǎn)換成列表。如:
>>> list("hello world")
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> list((1,2,3,4))
[1, 2, 3, 4]
7.int(x[,base])
int()函數(shù)把數(shù)字和字符串轉(zhuǎn)換成一個(gè)整數(shù),base為可選的基數(shù)。
>>> int(3.3)
3
>>> int(3L)
3
>>> int("13")
13
>>> int("14",15)
19
8.min(x[,y,z...])
min()函數(shù)返回給定參數(shù)的最小值,參數(shù)可以為序列。
>>> min(1,2,3,4)
1
>>> min((1,2,3),(2,3,4))
(1, 2, 3)
9.max(x[,y,z...])
max()函數(shù)返回給定參數(shù)的最大值,參數(shù)可以為序列。
>>> max(1,2,3,4)
4
>>> max((1,2,3),(2,3,4))
(2, 3, 4)
10.oct(x)
oct()函數(shù)可把給出的整數(shù)轉(zhuǎn)換成八進(jìn)制數(shù)。
>>> oct(8)
'010'
>>> oct(123)
'0173'
11.ord(x)
ord()函數(shù)返回一個(gè)字符串參數(shù)的ASCII碼或Unicode值。
>>> ord("a")
97
>>> ord(u"a")
97
12.str(obj)
str()函數(shù)把對(duì)象轉(zhuǎn)換成可打印字符串。
>>> str("4")
'4'
>>> str(4)
'4'
>>> str(3+2j)
'(3+2j)'
13.tuple(x)
tuple()函數(shù)把序列對(duì)象轉(zhuǎn)換成tuple。
>>> tuple("hello world")
('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')
>>> tuple([1,2,3,4])
(1, 2, 3, 4)
3.序列處理函數(shù)
1.常用函數(shù)中的len()、max()和min()同樣可用于序列。
2.filter(function,list)
調(diào)用filter()時(shí),它會(huì)把一個(gè)函數(shù)應(yīng)用于序列中的每個(gè)項(xiàng),并返回該函數(shù)返回真值時(shí)的所有項(xiàng),從而過濾掉返回假值的所有項(xiàng)。
>>> def nobad(s):
... return s.find("bad") == -1
...
>>> s = ["bad","good","bade","we"]
>>> filter(nobad,s)
['good', 'we']
這個(gè)例子通過把nobad()函數(shù)應(yīng)用于s序列中所有項(xiàng),過濾掉所有包含“bad”的項(xiàng)。
3.map(function,list[,list])
map()函數(shù)把一個(gè)函數(shù)應(yīng)用于序列中所有項(xiàng),并返回一個(gè)列表。
>>> import string
>>> s=["python","zope","linux"]
>>> map(string.capitalize,s)
['Python', 'Zope', 'Linux']
map()還可同時(shí)應(yīng)用于多個(gè)列表。如:
>>> import operator
>>> s=[1,2,3]; t=[3,2,1]
>>> map(operator.mul,s,t) # s[i]*t[j]
[3, 4, 3]
如果傳遞一個(gè)None值,而不是一個(gè)函數(shù),則map()會(huì)把每個(gè)序列中的相應(yīng)元素合并起來,并返回該元組。如:
>>> a=[1,2];b=[3,4];c=[5,6]
>>> map(None,a,b,c)
[(1, 3, 5), (2, 4, 6)]
4.reduce(function,seq[,init])
reduce()函數(shù)獲得序列中前兩個(gè)項(xiàng),并把它傳遞給提供的函數(shù),獲得結(jié)果后再取序列中的下一項(xiàng),連同結(jié)果再傳遞給函數(shù),以此類推,直到處理完所有項(xiàng)為止。
>>> import operator
>>> reduce(operator.mul,[2,3,4,5]) # ((2*3)*4)*5
120
>>> reduce(operator.mul,[2,3,4,5],1) # (((1*2)*3)*4)*5
120
>>> reduce(operator.mul,[2,3,4,5],2) # (((2*2)*3)*4)*5
240
5.zip(seq[,seq,...])
zip()函數(shù)可把兩個(gè)或多個(gè)序列中的相應(yīng)項(xiàng)合并在一起,并以元組的格式返回它們,在處理完最短序列中的所有項(xiàng)后就停止。
>>> zip([1,2,3],[4,5],[7,8,9])
[(1, 4, 7), (2, 5, 8)]
如果參數(shù)是一個(gè)序列,則zip()會(huì)以一元組的格式返回每個(gè)項(xiàng),如:
>>> zip((1,2,3,4,5))
[(1,), (2,), (3,), (4,), (5,)]
>>> zip([1,2,3,4,5])
[(1,), (2,), (3,), (4,), (5,)]
4.其他
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
()
{}
相關(guān)文章
使用Python實(shí)現(xiàn)畫一個(gè)中國地圖
今天小編就為大家分享一篇使用Python實(shí)現(xiàn)畫一個(gè)中國地圖,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-11-11pyqt 實(shí)現(xiàn)QlineEdit 輸入密碼顯示成圓點(diǎn)的方法
今天小編就為大家分享一篇pyqt 實(shí)現(xiàn)QlineEdit 輸入密碼顯示成圓點(diǎn)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-06-06Django Admin實(shí)現(xiàn)三級(jí)聯(lián)動(dòng)的示例代碼(省市區(qū))
多級(jí)菜單在很多上面都有應(yīng)用,這篇文章主要介紹了Django Admin實(shí)現(xiàn)三級(jí)聯(lián)動(dòng)(省市區(qū)),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-06-06

對(duì)sklearn的使用之?dāng)?shù)據(jù)集的拆分與訓(xùn)練詳解(python3.6)

tkinter如何獲取復(fù)選框(Checkbutton)的值

Python+Turtle實(shí)現(xiàn)繪制可愛的小倉鼠